.net core 集成 autofac.

1. Install

Install-Package Autofac
Install-Package Autofac.Extensions.DependencyInjection

2.Startup

2.1 增加成員

public IContainer ApplicationContainer { get; private set; }

2.2 Startup.ConfigureServices

返回值改為:IServiceProvider

末尾中增加:

//******************* autofac start ***********************
// Create the container builder.
var autofacBuilder = new ContainerBuilder();


autofacBuilder.RegisterType<TCPCollectorApplicationService>().As<ITCPCollectorApplicationService>();
autofacBuilder.Populate(services);
this.ApplicationContainer = autofacBuilder.Build();

return new AutofacServiceProvider(this.ApplicationContainer);
//******************* autofac start ***********************

3. Usage

3.1 构造注入

直接構造注入即可使用。

public TodoController(IKnowledgeApplicationService knowledgeApplicationService, ITCPCollectorApplicationService tcpCollectorApplicationService, IServiceProvider serviceProvider)
{
    KnowledgeApplicationService = knowledgeApplicationService;
    TCPCollectorApplicationService = tcpCollectorApplicationService;

    ServiceProvider = serviceProvider;
}

3.2 使用ServiceProvider获取。

var tcpSvc = ServiceProvider.GetService(typeof(ITCPCollectorApplicationService)) as ITCPCollectorApplicationService;
return Ok(tcpSvc.GetAll());

Ref:官方文檔: http://docs.autofac.org/en/latest/integration/aspnetcore.html#

posted @ 2017-05-27 14:41 _DN 阅读(...) 评论(...) 编辑 收藏