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 > Development >
Share
Shulou(Shulou.com)05/31 Report--
In this article, the editor introduces in detail "ASP.net core how to use Autofac to achieve generic dependency injection", the content is detailed, the steps are clear, and the details are handled properly. I hope that this article "ASP.net core how to use Autofac to achieve generic dependency injection" can help you solve your doubts.
What is generic dependency injection
Create two classes with generics and configure their dependencies, which will be inherited if the generics are the same for subclasses that inherit the two classes:
As shown above:
Two generic base classes are defined: BaseService and BaseRepository
If UserService and UserRpository inherit two base classes respectively, and the generics are both User, then they both inherit the dependency of the parent class.
Implementing generic dependency injection installation Autofac in .net core
Look at the project structure first.
IMyRepository defines the warehousing interface public interface IMyRepository where T: class {string GetTypeof ();} MyRepositoryBase warehousing implementation public class MyRepositoryBase: IMyRepository where T: class {public string GetTypeof () {return typeof (T) .Name; / / you can know the name of the generic type} through typeof.
Dependency injection classes common to CustomAutofacModule
Public class CustomAutofacModule: Module {public CustomAutofacModule (ContainerBuilder builder) {} / AutoFac registered class / protected override void Load (ContainerBuilder builder) {builder.RegisterGeneric (typeof (MyRepositoryBase)) .as (typeof (IMyRepository)) .InstancePerDependency () / / register warehouse generics / / builder.RegisterGeneric (typeof (MyRepositoryBase)) .as (typeof (IMyRepository)) .InstancePerDependency (); / / register warehouse generics with more than 2 generic parameters / / builder.RegisterType (). As (); / / normal dependency injection}} implement dependency injection in the Program declaration
Public class Program {public static void Main (string [] args) {CreateHostBuilder (args) .Build () .Run () } public static IHostBuilder CreateHostBuilder (string [] args) = > Host.CreateDefaultBuilder (args) / / use Autofac to implement dependency injection .UseServiceProviderFactory (new AutofacServiceProviderFactory ()) .ConfigureWebHostDe faults (webBuilder = > {ServiceProviderFactory ();});} modify Startup
Trigger CustomAutofacModule at run time
Public class Startup {public Startup (IConfiguration configuration) {Configuration = configuration;} public IConfiguration Configuration {get;} / / autofac added public ILifetimeScope AutofacContainer {get; private set;} public void ConfigureServices (IServiceCollection services) {services.AddControllers () } public void ConfigureContainer (ContainerBuilder builder) {/ / register our custom builder.RegisterModule (new CustomAutofacModule (builder)) directly with Autofac;} public void Configure (IApplicationBuilder app, IWebHostEnvironment env) {if (env.IsDevelopment ()) {app.UseDeveloperExceptionPage () } / / autofac added this.AutofacContainer = app.ApplicationServices.GetAutofacRoot (); app.UseRouting (); app.UseAuthorization (); app.UseEndpoints (endpoints = > {endpoints.MapControllers ();}) }} use [ApiController] [Route ("[controller]")] public class HomeController in the Home controller: ControllerBase {/ / public IMyRepository _ UserServer {get; set;} private readonly IMyRepository _ UserServer; private readonly IMyRepository _ RoleServer; public HomeController (IMyRepository UserServer, IMyRepository RoleServer) {_ UserServer = UserServer; _ RoleServer = RoleServer } [Route ("Get")] public string Get () {return _ UserServer.GetTypeof (); / / "user"; / /} [Route ("GetRole")] public string GetRole () {return _ RoleServer.GetTypeof (); / / "role"; / /}
You can see different places to implement different objects.
Outside:
I studied the use of generic dependency injection because I saw the IRepository implementation of the ABP framework.
ABP framework bar Autofac has been encapsulated as IocManager
So the ABP framework does not need to be introduced into the Autofac framework. You only need to declare dependency injection in the Initialize () method in the corresponding XXXCoreModule
IocManager.Register (typeof (IMyRepository), typeof (MyRepositoryBase), DependencyLifeStyle.Transient)
If there are more than 2 generics, it is IocManager.Register (typeof (IAmbientScopeProvider), typeof (DataContextAmbientScopeProvider), DependencyLifeStyle.Transient).
The role of DependencyLifeStyle.Transient
Transient: transient, either the scope is the whole process or the scope is a request, but the Transient here has no concept of scope. The most obvious difference between instantiation and instantiation of injection is that attribute injection is not available, and only constructor injection can be used.
Singleton: you can keep an instance in your process, that is, the most obvious difference between instantiating only once is that attribute injection is available.
Fan wai 2:
You have seen many tutorials that declare dependency injection in Startup without declaring the CustomAutofacModule class. But that's how core 2.0 is written. The following words in core 3.0will report errors.
Public static IContainer AutofacContainer;// This method gets called by the runtime. Use this method to add services to the container.public IServiceProvider ConfigureServices (IServiceCollection services) {/ / register services into IServiceCollection services.AddMvc (); ContainerBuilder builder = new ContainerBuilder (); / / populate services in services into Autofac. Builder.Populate (services); / / New module component registers builder.RegisterModule (); / / creates a container. AutofacContainer = builder.Build (); / / create AutofacServiceProvider return new AutofacServiceProvider (AutofacContainer) using containers;} read here, this article "how to implement generic dependency injection with ASP.net core using Autofac" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it before you can understand it. If you want to learn more about related articles, please follow the industry information channel.
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.