In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
Today, I will talk to you about how to use Autofac to replace the IOC container and implement attribute injection in ASP.NET Core. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
Today we will mainly talk about how to replace the IOC container with Autofac and implement property injection.
1. Replace the default IOC container with Autofac
First, we need to reference the relevant package from nuget.
Autofac
Autofac.Extensions.DependencyInjection (this package extends some classes of services provided by Microsoft. To facilitate the replacement of autofac)
Then, we modify the ConfigureServices code in Startup as follows:
Public IServiceProvider ConfigureServices (IServiceCollection services)
{
Services.AddMvc ()
Services.AddDbContext ()
Services.AddDirectoryBrowser ()
Var containerBuilder = new ContainerBuilder ()
ContainerBuilder.RegisterModule ()
ContainerBuilder.Populate (services)
Var container = containerBuilder.Build ()
Return new AutofacServiceProvider (container)
}
Here we use one of the functions of AutoFac, modular injection. That is, RegisterModule here, DefaultModule is our injection module, the code is very simple, as follows:
Public class DefaultModule: Module
{
Protected override void Load (ContainerBuilder builder)
{
/ / injection testing service
Builder.RegisterType () .As ()
}
}
To explain, in the above code, we configure IServiceProvider to parse from the Autofac container (setting up a valid Autofac service adapter).
It is then used throughout the framework to resolve controller dependencies and expose service locations for all other use cases on HttpContext.
This completes the preliminary Autofac container replacement. Let's create a controller to see the effect. The code is as follows:
Public class AutoDIController: Controller
{
Private readonly ITestService _ testService
Public AutoDIController (ITestService testService)
{
_ testService = testService
}
/ / GET: AutoDI
Public ActionResult Index ()
{
ViewBag.date = _ testService.GetList ("Name")
Return View ()
}
}
When the framework (through a service named DefaultControllerActivator) creates an instance of a controller, it parses all constructor dependencies of IServiceProvider. In the above code, it uses the Autofac container to parse the generated class.
So we can initially achieve the effect of replacing the IOC container..
However, the difference between this operation and asp.net MVC is that. The controller itself is not parsed from the container, so the service can only be parsed from its constructor parameters.
So。 This process prevents us from using some of the more advanced features of Autofac. For example, attribute injection (about the quality of attribute injection.. We will not discuss whether it is good or bad here.
two。 How to use the advanced features of Autofac, attribute injection.
Let's go back to the Autofac setup code and set the property injection as follows:
Var containerBuilder = new ContainerBuilder ()
/ / Modular injection
ContainerBuilder.RegisterModule ()
/ / attribute injection controller
ContainerBuilder.RegisterType () .PropertiesAutowired ()
ContainerBuilder.Populate (services)
The code for the injection module is modified as follows:
/ / attribute injection builder.RegisterType () .As () .PropertiesAutowired ()
Then modify our controller code as follows:
Public class AutoDIController: BaseController
{
Public ITestService _ testService {get; set;}
/ / GET: AutoDI
Public ActionResult Index ()
{
ViewBag.date = _ testService.GetList ("Name")
Return View ()
}
}
Here we eliminate the constructor of the controller.
When we run the code, we will find that _ testService is null, so the injection is not successful at all. We have explained the reasons for the failure above. But let's emphasize it.
Although the constructor dependency of the controller will be resolved by MVC from IServiceProvider (that is, our previous example of constructor injection)
But the instance of the controller itself (and its processing) is created and owned by the framework, not owned by the container.
So how do we change the creation and ownership of the controller itself?
We will find a way in Microsoft.Extensions.DependencyInjection. It's called AddControllersAsServices.
It translates as: convert the controller's host to a registered service (that is, the autofac we replaced).
But pay attention to.. Although the owner of the control has been changed to autofac, we still cannot use the relevant attribute injection method.
So, let's go to GITHUB to see the source code of this method is as follows. This is the benefit of open source.):
Public static IMvcBuilder AddControllersAsServices (this IMvcBuilder builder)
{
If (builder = = null)
{
Throw new ArgumentNullException (nameof (builder))
}
Var feature = new ControllerFeature ()
Builder.PartManager.PopulateFeature (feature)
Foreach (var controller in feature.Controllers.Select (c = > c.AsType ()
{
Builder.Services.TryAddTransient (controller, controller)
}
Builder.Services.Replace (ServiceDescriptor.Transient ())
Return builder
}
We will find the last sentence..
Builder.Services.Replace (ServiceDescriptor.Transient ())
It means to replace DefaultControllerActivator with ServiceBasedControllerActivator (meaning that the framework will now try to parse the controller instance from IServiceProvider)
.. Now the truth has finally come out..
We only need to modify the code of the configuration service as follows:
Public IServiceProvider ConfigureServices (IServiceCollection services)
{
/ / replace the controller owner
Services.Replace (ServiceDescriptor.Transient ())
Services.AddMvc ()
Services.AddDbContext ()
Services.AddDirectoryBrowser ()
Var containerBuilder = new ContainerBuilder ()
ContainerBuilder.RegisterModule ()
/ / using attribute injection controller
ContainerBuilder.RegisterType () .PropertiesAutowired ()
/ / containerBuilder.RegisterTypes (feature.Controllers.Select (ti = > ti.AsType ()). ToArray (). PropertiesAutowired ()
ContainerBuilder.Populate (services)
Var container = containerBuilder.Build ()
Return new AutofacServiceProvider (container)
}
Note that the replacement method must be before addMVC..
Then we run our controller code. The effect is as shown in the figure:
As shown in the figure, _ testService has been instantiated. It means that our attribute injection is successful.
After reading the above, do you have any further understanding of how to use Autofac to replace the IOC container and implement attribute injection in ASP.NET Core? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.