0

为了更好地理解如何将 Autofac 与 json/xml 配置一起使用,我正在创建一个支持插件的小型示例应用程序。该解决方案包含以下程序集:(1) BusinessLogic.Interfaces、(2) BusinessLogic1、(3) BusinessLogic2、(4) DependencyInjection 和 (5) 视图。后者是一个简单的 Winforms 程序集,我可以使用它来测试应用程序。

程序集“BusinessLogic.Interfaces”仅包含一个接口 IFoo。这两个 BusinessLogic 程序集都只包含一种类型,Foo,它们都实现了 IFoo。有了这个设置,我可以配置 DI 容器来给我一个合适的 IFoo 实现。按照Autofac 站点上的文档,我得到以下用于读取配置文件的代码

private static ContainerBuilder CreateBuilderFromConfigFile()
{
    var config = new configurationBuilder();
    config.AddJsonFile("autofac.json"); //BTW, requires m_a_n_y nuget packages
    var module = new ConfigurationModule(config.Build());
    var builder = new ContainerBuilder();
    builder.RegisterModule(module);
    return builder;
}

具有以下配置

{
  "components": [{
     "type": "BusinessLogic2.Foo, BusinessLogic.Interfaces",
     "services": [{
        "type": "BusinessLogic.Interfaces.IFoo, BusinessLogic.Interfaces"
    }]
  }]
}

在类 DependencyInjection.DiContainer 中,我使用

 public void Initialize(Containerbuidler builder)
 {
     Container = builder.Build(); //definition 'Container' not shown here
 }

当程序集视图链接到 BusinessLogic1 和 BusinessLogic2 时,此代码有效。在 json 文件中,我可以轻松更改要使用的实现。

如果我从视图程序集的引用中删除 BusinessLogic2,我会遇到问题。我在命令“builder.Build()”上得到一个 InvalidOperationExecption。这是合理的,因为请求的类型位于尚未加载的程序集中。因此我使用反射加载程序集。按照本教程,我添加了以下方法

private static void LoadAddons(string searchInFolder, string pattern)
{
   foreach(var fileName in Directory.GetFiles(searchInFolder, pattern))
   {
      Assembly.LoadFrom(fileName);
   }
}

现在,在 main 方法中,我首先调用方法 LoadAddons,然后调用 CreateBuidlerFromConfigFile。在 Visual Studio 的模块视图(调试 -> Windows -> 模块)中,我看到 BusinessLogic2 已加载,但仍然存在 InvalidOperationException。

编辑异常消息是:“Autofac.Configuration.dll 中发生'System.InvalidOperationException' 类型的未处理异常附加信息:找不到类型'BusinessLogic2.Foo,BusinessLogic'。它可能需要装配资格,例如“MyType , MyAssembly”。如何告诉使用 xml/json 配置的 Autofac 注册一个动态加载的类型?

4

0 回答 0