如何在MVC Core和AutoFac中使用Property Injection

Siy*_*ang 5 c# autofac property-injection asp.net-core-mvc .net-core

我可以在MVC Core中轻松使用Constructor Parameter Injection.但是不支持Property Injection.我尝试使用AutoFac但也失败了.
那么如何在MVC Core中使用Property Injection.
这是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); 
Run Code Online (Sandbox Code Playgroud)

Hir*_*sai 3

在 dotnet core 中,您需要进行以下更改才能使 Autofac 工作:IContainer在应用程序中添加公共 AutofacStartup.cs

public IContainer ApplicationContainer { get; private set; }
Run Code Online (Sandbox Code Playgroud)

更改ConfigureServicesStartup.csreturn IServiceProvider,进行所有注册,使用 填充容器中的框架服务builder.Populat(services);。请注意,您不需要这样做builder.RegisterType<HomeController>().PropertiesAutowired();

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    builder.Populate(services);
    ApplicationContainer = container;
    return new AutofacServiceProvider(ApplicationContainer);
}
Run Code Online (Sandbox Code Playgroud)

您还需要确保通过在Configure方法中执行此操作来在停止的应用程序上处置容器。

public void Configure(IApplicationBuilder app, IApplicationLifetime appLifetime)
{
    app.UseMvc();           
    appLifetime.ApplicationStopped.Register(() => ApplicationContainer.Dispose());
}
Run Code Online (Sandbox Code Playgroud)

执行此操作后 - 您的控制器应该自动获取自动连接的属性。