Autofac 注入配置

新建一个继承于Autofac.Module的AutofacModuleRegister类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  public class AutofacModuleRegister : Autofac.Module
{
//重写Autofac管道Load方法,在这里注册注入
protected override void Load(ContainerBuilder builder)
{
//注册Service中的对象,Service中的类要以Service结尾,否则注册失败
builder.RegisterAssemblyTypes(Assembly.Load("Power.Server")).Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces();
//注册Repository中的对象,Repository中的类要以Repository结尾,否则注册失败
builder.RegisterAssemblyTypes(Assembly.Load("Power.Data")).Where(a => a.Name.EndsWith("Repository")).AsImplementedInterfaces();

builder.RegisterType<WxPayService>().Named<IPayService>(typeof(WxPayService).Name);

builder.RegisterType<AliPayService>().Named<IPayService>(typeof(AliPayService).Name);

builder.RegisterType<PowerControlConnectionStrings>().Named<IConnectionStrings>(typeof(PowerControlConnectionStrings).Name);
}
}

在StartUp类中新建RegisterAutofac方法

1
2
3
4
5
6
7
8
9
10
11
12
13
private IServiceProvider RegisterAutofac(IServiceCollection services)
{
//实例化Autofac容器
var builder = new ContainerBuilder();
//将Services中的服务填充到Autofac中
builder.Populate(services);
//新模块组件注册
builder.RegisterModule<AutofacModuleRegister>();
//创建容器
var Container = builder.Build();
//第三方IOC接管 core内置DI容器
return new AutofacServiceProvider(Container);
}

在ConfigureServices方法内调用RegisterAutofac方法

1
2
3
4
public IServiceProvider ConfigureServices(IServiceCollection services)
{
return RegisterAutofac(services);
}

使用样例

1
2
3
4
5
6
7
8
9
private readonly IPersonService _personService;
private readonly IPayService _wxPayService;
private readonly IPayService _aliPayService;
public HomeController(IPersonService personService, IComponentContext componentContext, IConnectionStrings connection)
{
_personService = personService;
_wxPayService = componentContext.ResolveNamed<IPayService>(typeof(WxPayService).Name);
_aliPayService = componentContext.ResolveNamed<IPayService>(typeof(AliPayService).Name);
}