我可以在 MVC Core 中轻松使用构造函数参数注入。但不支持属性注入。我尝试使用 AutoFac 但也失败了。
那么如何在MVC Core中使用属性注入。
这是 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 工作:
添加公共 AutofacIContainer
在你的申请中Startup.cs
public IContainer ApplicationContainer { get; private set; }
Change ConfigureServices
in Startup.cs
回来IServiceProvider
,完成所有注册,使用以下命令填充容器中的框架服务builder.Populat(services);
。请注意,您不需要这样做builder.RegisterType<HomeController>().PropertiesAutowired();
public IServiceProvider ConfigureServices(IServiceCollection services)
{
builder.Populate(services);
ApplicationContainer = container;
return new AutofacServiceProvider(ApplicationContainer);
}
您还需要确保在停止的应用程序上处置容器,方法是在您的应用程序中执行此操作Configure
method.
public void Configure(IApplicationBuilder app, IApplicationLifetime appLifetime)
{
app.UseMvc();
appLifetime.ApplicationStopped.Register(() => ApplicationContainer.Dispose());
}
执行此操作后 - 您的控制器应该自动获取自动连接的属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)