【发布时间】:2021-09-14 08:52:47
【问题描述】:
我有多个项目如下:
1- 基础设施:这是 classLibrary 项目,包含基础设施类、接口等。
2- Runable Project:这是asp.net core 5项目,用于启动其他业务项目,参考Infrastructure项目
3- 业务解决方案:这有多个用于api, service, domain, ... 层的类库项目
Infrastructure项目中有如下界面:
using Microsoft.Extensions.DependencyInjection;
namespace Infrastructure
{
public interface IModuleLoader
{
void Register(IServiceCollection serviceCollection);
}
}
在Business.Api 项目中有一个实现IModuleLoader 接口的类
namespace Business.Api
{
public class BusinessModuleLoader : IModuleLoader
{
public void Register(IServiceCollection services)
{
services.AddControllers().AddApplicationPart(this.GetType().Assembly);
//...
}
}
}
在Runable项目中有这个类用于加载业务Assembly项目
public static class ModuleLoaderHelper
{
public static void LoadModules(this IServiceCollection services)
{
AutoLoading(services);
}
private static void AutoLoading(IServiceCollection services)
{
var path = AppDomain.CurrentDomain.BaseDirectory;
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] fis = di.GetFiles("Business.Api.dll");
var mtype = typeof(Infrastructure.IModuleLoader);
foreach (var f in fis)
{
try
{
var loadContext = new PluginLoadContext(f.FullName);
var asm = loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(f.FullName)));
var moduleLoader = asm.GetTypes().FirstOrDefault(p => mtype.IsAssignableFrom(p));
if (moduleLoader == null)
continue;
Infrastructure.IModuleLoader loader = (Infrastructure.IModuleLoader)Activator.CreateInstance(moduleLoader);
loader.Register(services);
}
catch (Exception exp)
{
Console.WriteLine(exp.Message + exp.StackTrace);
}
}
}
class PluginLoadContext : AssemblyLoadContext
{
private AssemblyDependencyResolver _resolver;
public PluginLoadContext(string pluginPath)
{
_resolver = new AssemblyDependencyResolver(pluginPath);
}
protected override Assembly Load(AssemblyName assemblyName)
{
string assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName);
if (assemblyPath != null)
{
return LoadFromAssemblyPath(assemblyPath);
}
return null;
}
protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
{
string libraryPath = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName);
if (libraryPath != null)
{
return LoadUnmanagedDllFromPath(libraryPath);
}
return IntPtr.Zero;
}
}
}
}
已加载的Business.Api 程序集和BusinessModuleLoader 类型存在于已加载的程序集中,但是
在这行代码中不匹配 var moduleLoader = asm.GetTypes().FirstOrDefault(p => mtype.IsAssignableFrom(p)); 和变量 moduleLoader 是 null
我该如何解决这个问题?
【问题讨论】:
-
不应该
di.GetFiles("Business.Api.dll");更像di.GetFiles("Business.*.dll");???你也不应该使用loadContext.Load而不是loadContext.LoadFromAssemblyName -
@Stamos 此行用于模式匹配过滤器搜索程序集
di.GetFiles("Business.*.dll");
标签: c# asp.net-web-api .net-core .net-assembly