Read modules from web.config in autofac to change container configuration according to solution configurations
我已经创建了一些Autofac模块...现在我想使用web.config在容器中注册其中一些...在我的web.config中,我写了:
1 2 3 4 5 | <modules> <module type="DebugModuleTest1"></module> <module type="DebugModuleTest2"></module> </modules> </autofac> |
现在,我必须构建我的容器。但是autofac文档对我来说还不清楚。我不明白读取模块和构建容器所要做的事情。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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,所以没有可用的
谁能帮我吗?
编辑
我在web.config上发现了有趣的保存配置,因为这样可以根据解决方案配置(您知道经典的web.debug.config,web.release.config等)"更改" web.config。
那可以帮助我注册正确的模块,从而避免使用指令(#if bla bla bla,...)或仅使用条件...
我已经在使用模块,但是我认为正确的解决方案不是在模块内部添加属性来选择要根据要在其中部署项目的所选环境解析的组件。
我只是在阅读此示例时想到了此解决方案(顺便说一句,"覆盖的灵活性"仍然引用
在4.0版本的配置中,您不会在web.config中存储任何内容。全部在单独的XML或JSON文件中。我建议使用JSON。该文档概述得很好:
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"。如果您跳过,您可能会在" 4.0之前的版本"中结束,认为仍然可以在4.0版本中使用。不会的从您对另一个问题的评论中看来,您可能第一次错过了一些东西。
在快速入门部分中花一些时间。该部分同时包含C#和JSON代码,显示了工作方式。同样,跳过这一点很容易。
如果文档显示的示例不足,请查看Autofac.Configuration存储库中的单元测试,尤其是充满测试文件的文件夹,其中显示了我们在测试中使用的XML和JSON格式的示例。
最后...三个提示: