一、基本配置
1、通过配置的方式使用Autofac
<?xml version="1.0"?> <configuration> <configSections> <section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration"/> </configSections> <autofac defaultAssembly="ConsoleApplication3"> <components> <component type="ConsoleApplication3.Worker, ConsoleApplication3" service="ConsoleApplication3.IPerson" /> </components> </autofac> </configuration>
2、通过RegisterModule方式使用配置文件中的信息
static void Main(string[] args) { ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType<AutoFacManager>(); builder.RegisterModule(new ConfigurationSettingsReader("autofac")); using (IContainer container = builder.Build()) { AutoFacManager manager = container.Resolve<AutoFacManager>(); manager.Say(); } Console.ReadKey(); }
3、通过Register的方式
builder.RegisterModule(new ConfigurationSettingsReader("autofac")); builder.Register(c => new AutoFacManager(c.Resolve<IPerson>()));
【注意】:在web.config或app.config中配置针对Autofac.Configuration低于4.0才行
针对4.0及以上版本
官方推荐使用单独json或xml文件配置
http://docs.autofac.org/en/latest/configuration/xml.html#quick-start
JSON格式
{ "defaultAssembly": "Autofac.Example.Calculator", "components": [{ "type": "Autofac.Example.Calculator.Addition.Add, Autofac.Example.Calculator.Addition", "services": [{ "type": "Autofac.Example.Calculator.Api.IOperation" }], "injectProperties": true }, { "type": "Autofac.Example.Calculator.Division.Divide, Autofac.Example.Calculator.Division", "services": [{ "type": "Autofac.Example.Calculator.Api.IOperation" }], "parameters": { "places": 4 } }] }
xml格式
<?xml version="1.0" encoding="utf-8" ?> <autofac defaultAssembly="Autofac.Example.Calculator"> <components name="0"> <type>Autofac.Example.Calculator.Addition.Add, Autofac.Example.Calculator.Addition</type> <services name="0" type="Autofac.Example.Calculator.Api.IOperation" /> <injectProperties>true</injectProperties> </components> <components name="1"> <type>Autofac.Example.Calculator.Division.Divide, Autofac.Example.Calculator.Division</type> <services name="0" type="Autofac.Example.Calculator.Api.IOperation" /> <injectProperties>true</injectProperties> <parameters> <places>4</places> </parameters> </components> </autofac>
使用代码
// Add the configuration to the ConfigurationBuilder. var config = new ConfigurationBuilder(); config.AddJsonFile("autofac.json"); // Register the ConfigurationModule with Autofac. var module = new ConfigurationModule(config.Build()); var builder = new ContainerBuilder(); builder.RegisterModule(module);
这里我遇到一个问题,就是
config.AddJsonFile("autofac.json")
这个方法无法被识别到,后来在网上找到帮助,却是一个类库Microsoft.Extensions.Configuration.Json.dll
添加了这个累计就可以了