如何在 MVC Core 和 AutoFac 中使用属性注入 [英] How to use Property Injection in MVC Core and AutoFac
问题描述
我可以在 MVC Core 中轻松使用构造函数参数注入.但是不支持属性注入.我尝试使用 AutoFac 但也失败了.
那么如何在 MVC Core 中使用属性注入.
这是带有 AutoFac 的代码
I can use Constructor Parameter Injection easily In MVC Core. But Property Injection is not supported.I try use AutoFac but fail too.
So how to use Property Injection in MVC Core.
Here is the code with AutoFac
services.AddMvc();
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<Test2>().As<ITest>();
builder.RegisterType<HomeController>().PropertiesAutowired();
builder.Populate(services);
var container = builder.Build();
//The following code works
HomeController test2 = container.Resolve<HomeController>();
return new AutofacServiceProvider(container);
推荐答案
在 dotnet core 中,您需要进行以下更改才能使 Autofac 工作:在您的应用程序 Startup.cs
In dotnet core, you need to make the following changes to make Autofac work:
Add a public Autofac IContainer
in your application Startup.cs
public IContainer ApplicationContainer { get; private set; }
更改 Startup.cs
中的 ConfigureServices
以返回 IServiceProvider
,完成所有注册,使用 builder.Populat(services);
.请注意,您无需执行 builder.RegisterType
Change ConfigureServices
in Startup.cs
to return IServiceProvider
, do all your registrations, populate the framework services in your container by using builder.Populat(services);
. Please note that there is no need for you to do builder.RegisterType<HomeController>().PropertiesAutowired();
public IServiceProvider ConfigureServices(IServiceCollection services)
{
builder.Populate(services);
ApplicationContainer = container;
return new AutofacServiceProvider(ApplicationContainer);
}
您还需要通过在 Configure
方法中执行此操作,确保在已停止的应用程序上处置容器.
You will also need to make sure you dispose the container on application stopped by doing this in your Configure
method.
public void Configure(IApplicationBuilder app, IApplicationLifetime appLifetime)
{
app.UseMvc();
appLifetime.ApplicationStopped.Register(() => ApplicationContainer.Dispose());
}
执行此操作后 - 您的控制器应自动获取自动装配的属性.
After you do this - your controllers should automatically get the properties autowired.
这篇关于如何在 MVC Core 和 AutoFac 中使用属性注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!