In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the knowledge of "how to use ASP.NET 's Core injection framework". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Catalogue
I. IoC framework
II. IoC-Autofac
3. The use of native DI in NET Core
IV. Use of Autofac
5. Batch injection
I. IoC framework
Let's start with the common Ioc framework.
Autofac: at present, net uses more, and many big guys' projects prefer the framework of choice.
Ninject: it's seldom used, and I've seen it in early articles.
Unity: it's quite common. It's useful in many places.
Core: it is quite convenient when the business logic is not too complex in Core.
II. IoC-Autofac
Autofac is one of the most popular IOC frameworks in .NET, and it is said to be the fastest one.
Advantages:
It is closely related to the C # language, which means that many programming methods in C # can be used by Autofac.
The low learning curve is very easy to learn, as long as you understand the concepts of IoC and DI and when you need to use them.
XML.Json configuration support.
Automatic assembly.
Integrate with Asp.Net MVC.
Microsoft's Orchad open source program uses Autofac, from which we can see its convenience and power.
Most articles that talk about the Autofac framework will mention the above advantages, which shows that the framework is excellent.
3. The use of native DI in NET Core
1. First create an ASP.Net Core Web Api project (selected. NET 5. 0), the whole is as follows, and the red part is the part that comes with DI in Core.
two。 Create a new class library project and add an interface file and a class file respectively.
Interface:
Public interface ISayHelloService {string SayHello (string name);}
Class:
Public class EnglishSayHelloService: ISayHelloService {public string SayHello (string name) {return $"Hello, {name}!";}}
3. Inject it into the ConfigureServices method in Startup.
Services.AddScoped ()
4. Then use the service you just injected into the controller.
[Route ("api/ [controller] / [action]")] [ApiController] public class HelloController: ControllerBase {public readonly ISayHelloService sayHelloService; public HelloController (ISayHelloService sayHelloService) {this.sayHelloService = sayHelloService;} [HttpGet] public string CoreDI () {return sayHelloService.SayHello ("CoreDI");}}
Note: routing access address, when there is a 404 error, it may be a routing problem. The route can be modified at [Route ("api/ [controller] / [action])] according to your actual needs.
5. Access test.
The interface testing software used here is Postman,Api testing, which can be found on the Internet. If you can't find me, please contact me.
IV. Use of Autofac
1. Create a new ASP.Net Core Web Api project (selected. NET 5. 0) to distinguish between the DI that comes with the previous Core.
two。 Citing the package referencing Autofac, look at the number of downloads, it is still very wow.
3. Using Autofac to implement dependency injection in Program
Public class Program {public static void Main (string [] args) {CreateHostBuilder (args). Build (). Run ();} public static IHostBuilder CreateHostBuilder (string [] args) = > Host.CreateDefaultBuilder (args) .ConfigureWebHostDefaults (webBuilder = > {webBuilder.UseStartup ();});}
4. Add a method to the Startup class: ConfigureContainer to inject our previous service.
Public class Startup {public Startup (IConfiguration configuration) {Configuration = configuration;} public IConfiguration Configuration {get;} public void ConfigureServices (IServiceCollection services) {services.AddControllers ();} / / inject public void ConfigureContainer (ContainerBuilder builder) {builder.RegisterType () .As () here } public void Configure (IApplicationBuilder app, IWebHostEnvironment env) {if (env.IsDevelopment ()) {app.UseDeveloperExceptionPage ();} app.UseRouting (); app.UseAuthorization (); app.UseEndpoints (endpoints = > {endpoints.MapControllers ()) );}}
5. The controller basically does not need to be changed here.
[Route ("api/ [controller] / [action]")] [ApiController] public class HelloController: ControllerBase {public readonly ISayHelloService sayHelloService; public HelloController (ISayHelloService sayHelloService) {this.sayHelloService = sayHelloService;} [HttpGet] public string CoreDI () {return sayHelloService.SayHello ("AutofacDI");}}
6. Run the project and continue to test the interface with Postman.
Well, I've basically finished talking about the basic use of Autofac, isn't it still quite simple?
5. Batch injection
A few simple services are written to be acceptable, and when there are dozens or even hundreds of services, it's scary to think about it. This has to say that when it comes to batch injection, the advantages of Autofac are reflected.
1. Add an interface, and a class to the service, respectively.
Interface:
Public interface IUseAutofacService {string UseAutofac (string name);}
Class:
Public class UseAutofacService: IUseAutofacService {public string UseAutofac (string name) {return $"{name} batch injection test!" ;}}
two。 Go back to our previous Startup class to modify the method: ConfigureContainer.
Public void ConfigureContainer (ContainerBuilder builder) {/ / builder.RegisterType () .As (); / / Service project assembly Assembly service = Assembly.Load ("Autofac.Service"); / / Service interface project assembly Assembly iservice = Assembly.Load ("Autofac.Service") Builder.RegisterAssemblyTypes (service, iservice) .Where (n = > n.FullName.EndsWith ("Service") & &! n.IsAbstract) .InstancePerLifetimeScope () .AsImplementedInterfaces ();}
Note: if the service that needs to be injected does not have an interface for IXXXService, then builder.RegisterAssemblyTypes only needs to pass an assembly. If the service and the interface are in the same project, two assemblies will be passed.
3. Next, make a slight modification in the controller just now.
[Route ("api/ [controller] / [action]")] [ApiController] public class HelloController: ControllerBase {public readonly ISayHelloService sayHelloService; public readonly IUseAutofacService useAutofacService; public HelloController (ISayHelloService _ sayHelloService, IUseAutofacService _ useAutofacService) {this.sayHelloService = _ sayHelloService; this.useAutofacService = _ useAutofacService } [HttpGet] public string AutofacDI () {return sayHelloService.SayHello ("AutofacDI");} public string BathAutofacDI () {var name = sayHelloService.SayHello ("AutofacDI"); return useAutofacService.UseAutofac (name);}}
4. Test the injection with Postman.
That's all for "how to use ASP.NET 's Core injection Framework". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.