【问题标题】:Autofac + OWIN Service Resolution IssueAutofac + OWIN 服务解决问题
【发布时间】:2016-07-13 08:16:16
【问题描述】:

我正在从“插件”文件夹加载程序集并动态注册一些实现。

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)'.",

可能是什么问题?

编辑:从容器中解析失败。

【问题讨论】:

  • 当您尝试直接从容器解析 ITestService 时会发生什么?
  • 无法解决。

标签: asp.net-web-api owin autofac


【解决方案1】:

我认为您在运行 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

【讨论】:

  • 那个 AssemblyPreloader 类非常有用。 :) 我最终决定在运行时构建 ApiControllers 并使用 Mediator 将请求分派给正确的处理程序。经过几次更改后,一切正常,但我不确定是什么问题。
猜你喜欢
  • 1970-01-01
  • 2011-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-29
相关资源
最近更新 更多