在startup类中引用静态容器是个坏主意。这样,就在控制器和启动之间引入了紧密耦合。构造函数参数应该满足控制器依赖关系。接受
http://docs.autofac.org/en/v4.0.0/integration/aspnetcore.html
这个
Startup.ConfigureServices
方法可以选择性地返回
IServiceProvider
实例,它允许您将Autofac插件到ASP。NET Core依赖项注入框架:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var builder = new ContainerBuilder();
builder.RegisterType<MyType>().As<IMyType>();
builder.Populate(services);
this.ApplicationContainer = builder.Build();
return new AutofacServiceProvider(this.ApplicationContainer);
}
初始化容器后,Autofac将自动解析构造函数参数:
public class MyController
{
private readonly IMyType theType;
public MyController(IMyType theType)
{
this.theType = theType;
}
....
}