从 autofac 中的 web.config 中读取模块以根据解决方案配置更改容器配置

Read modules from web.config in autofac to change container configuration according to solution configurations

我创建了一些 Autofac 模块...现在我想使用 web.config 在我的容器中注册其中一些...在我的 web.config 中我写了:

<autofac defaultAssembly="Autofac.Example">
  <modules>
    <module type="DebugModuleTest1"></module>
    <module type="DebugModuleTest2"></module>
  </modules>
</autofac>

现在我必须构建我的容器。但是我不清楚 autofac 文档。我不明白我需要做什么来阅读我的模块和构建容器。

public class MyCustomContainer
{
    public void Build(HttpConfiguration config)
    {            
        var builder = new ContainerBuilder();

        Microsoft.Extensions.Configuration.ConfigurationBuilder x = new Microsoft.Extensions.Configuration.ConfigurationBuilder();
        //var sec = x.AddInMemoryCollection().Build().GetSection("autofac");
        // var y = x.AddXmlFile("Web.config");

        var y = new ConfigurationBuilder().SetBasePath(AppDomain.CurrentDomain.BaseDirectory);
        var z = y.AddXmlFile("Web.Config");


        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
    }
}

我使用的是最新版本的 Autofac,所以我没有可用的 ConfigurationSettingsReader class。

有人能帮帮我吗?

编辑

我在 web.config 上发现了有趣的保存配置,因为这样我可以 "change" web.config 根据我的解决方案配置(你知道, classic web.debug.config, web.release.config, 等)...

这可以帮助我注册正确的模块,避免使用指令(#if bla bla bla,...)或简单的条件...

我已经在使用模块,但我认为正确的解决方案是在模块内添加 属性 以根据我要部署项目的所选环境选择要解析的组件。 我只是想到这个解决方案阅读这个 example (By the way, Flexibility to Override 仍然指的是 ConfigurationSettingsReader。可以吗?)

在 4.0 版本的配置中,您不会在 web.config 中存储任何内容。全部在单独的 XML 或 JSON 文件中。我推荐 JSON。 The documentation 概述得很好:

If you were using the app.config or web.config based configuration available before, you will need to migrate your configuration to the new format and update the way you set configuration with your application container.

我们实际上花了很多时间尝试尽可能多地记录,所以虽然肯定 有很多 尽量不要 "TL;DR" 它。如果你跳过,你很可能会在 "pre 4.0" 部分结束,认为它仍然适用于 4.0 的东西。它不会。从 看来,您可能在第一次通过时错过了一些东西。

花一些时间在快速入门部分。该部分同时包含 C# 和 JSON 代码来展示其工作原理。同样,跳过它很容易。

如果文档没有显示足够的示例,请查看 Autofac.Configuration repo, especially the folder full of test files 中的单元测试,其中显示了我们在测试中使用的 XML 和 JSON 格式的示例。

最后...三个提示:

  1. 配置不是代码的特性对特性​​的替代。如果你想做一些惊人的、疯狂的、基于逻辑的东西,那么坚持modules, 可能需要一些配置来注册模块。
  2. 熟悉 Autofac 和 DI 术语。 如果您是 DI 或 Autofac 的新手,"components," "services," 和其他术语会造成混淆。配置使用这些术语,这意味着您可能看不到您正在查看的内容。花时间看文档。 The getting started page 包括一些术语的介绍。
  3. 了解新的 Microsoft 配置系统。 There is separate doc about that 由 Microsoft 维护。他们的文档解释了从如何根据环境更改配置到创建自定义配置提供程序的所有内容。 Autofac 站在配置巨人的肩膀上——我们不必再构建这种灵活性,因为它是从新的配置系统中免费获得的。