1. Install
Install-Package AutofacInstall-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#
相关文章:
使用 Autofac 进行依赖注入
ASP.NET Core依赖注入解读&使用Autofac替代实现
ASP.NET Core 整合Autofac和Castle实现自动AOP拦截
依赖注入之Autofac使用总结
原文地址:http://www.cnblogs.com/pengzhen/p/6912823.html
.NET社区新闻,深度好文,微信中搜索dotNET跨平台或扫描二维码关注