Autofac + OWIN 服务解决问题

Autofac + OWIN Service Resolution Issue

我正在从 "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)'.",

可能是什么问题?

编辑:从容器解析失败。

我认为当您 运行 Assembly.LoadFile(asmfile) 时,您可能会加载具有相同标识的程序集两次。这会导致您尝试解析的 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