我从“plugins”文件夹加载程序集并动态注册一些实现。
var appPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var pluginsPath = Path.Combine(appPath, path);
var asmfiles = Directory.EnumerateFiles(pluginsPath, "*.dll", SearchOption.AllDirectories);
foreach(var asmfile in asmfiles)
{
Assembly.LoadFile(asmfile);
}
加载所有程序集后,我继续注册服务:
builder.RegisterAssemblyTypes(asms)
.Where(t => typeof(IValidator).IsAssignableFrom(t))
.AsClosedTypesOf(typeof(IValidator<>));
builder.RegisterAssemblyTypes(asms)
.Where(t => typeof(IService).IsAssignableFrom(t) && t.IsClass)
.AsImplementedInterfaces()
.AsSelf();
为了确保,我记录了所有注册:
container.ComponentRegistry
.Registrations
.SelectMany(x => x.Services)
.Select(x => x.Description)
2016-07-13 09:58:52.5673 TRACE: Registered services:
Services.Test.ITestService
ServiceModel.IService
Services.Test.TestService
2016-07-13 09:58:52.5673 TRACE: Registered validators:
TestRequestValidator
问题是,Autofac似乎无法在其构造函数中创建具有ITestService
依赖关系的控制器。
"type": "Autofac.Core.DependencyResolutionException",
"message": "None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'ApiHostService.Controllers.EchoController' can be invoked with the available services and parameters: Cannot resolve parameter 'Services.Test.ITestService testService' of constructor 'Void .ctor(Services.Test.ITestService)'.",
可能是什么问题?
编辑:从容器中解析失败。
答案 0 :(得分:1)
我认为在运行Assembly.LoadFile(asmfile)时,可能会加载具有相同标识的程序集两次。这会导致您尝试解决的ITestService(这是项目引用中的那个)与您在容器中加载的ITestService(作为单独的程序集加载的ITestService)不同。
请您尝试使用Assembly.LoadFrom(asmfile)
吗?
看到这个问题: Difference between LoadFile and LoadFrom with .NET Assemblies?
你也可以使用这个程序集预加载器,它可以实现你想要的而不需要加载重复项: https://github.com/zidad/net-tools/blob/master/src/Net.Core/Reflection/AssemblyPreloader.cs