如何在MVC Core和AutoFac中使用属性注入

编程入门 行业动态 更新时间:2024-10-25 12:28:35
本文介绍了如何在MVC Core和AutoFac中使用属性注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我可以在MVC Core中轻松使用构造函数参数注入。但是不支持Property Injection。我尝试使用AutoFac但也失败。 那么如何在MVC Core中使用Property Injection。 这是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核心中,您需要进行以下更改使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; }

在<$ c $中更改 ConfigureServices c> Startup.cs 返回 IServiceProvider ,进行所有注册,并使用 builder填充容器中的框架服务.Populat(services); 。请注意,您不需要执行 builder.RegisterType< HomeController>()。PropertiesAutowired();

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); }

您还需要确保在处理停止的应用程序上处理容器

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中使用属性注入

本文发布于:2023-11-15 10:35:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1593665.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   如何在   Core   MVC   AutoFac

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!