In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article shows you a sample analysis of ASP.NET Core injecting multiple service implementation classes, which is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
Foreword:
Dependency injection plays an important role in ASP.NET Core, and it is also a high-end programming idea. Its general principle is: you can send me whatever I want. Instances of service types are automatically managed by the container without the need for us to explicitly handle them in the code.
Therefore, with dependency injection, your programming thinking will have to change. In the past, many functional types (such as an encrypted and decrypted class) like to be defined as static, but with dependency injection, you should avoid using static types and leave it to the service container to manage it for you. As long as you use it, you will find that dependency injection is very convenient.
The primary play of dependency injection is also a relatively standard game, which has two modes:
Ten generations of single-pass mode: an interface corresponds to a class, for example, interfaces IA and IB are defined first, then class An implements IA and class B implements IB. one-for-one. It can also be an abstract class (or base class) E, and then F inherits the E class.
Cut-off mode: write a class directly and add it to the service container without considering derivation.
Here, take a look at an example.
1. Define an interface public interface IPlayGame {void Play ();}
Then, write a class to implement it.
Public class NBPlayGame: IPlayGame {public void Play () {Console.WriteLine. ;}}
We know that the so-called service classes are actually ordinary classes, which are generally used to perform certain functions, such as calculating MD5 values. Next, remember that the Startup class has a ConfigureServices method, yes, in this guy, register the service we just had (that is, add it to the ServiceCollection collection).
Public void ConfigureServices (IServiceCollection services) {services.AddTransient ();}
It is simple to add, one-to-one types, and the IPlayGame interface corresponds to the NBPlayGame class. There are three methods you can call when adding, which actually corresponds to the lifecycle of the service class in the container.
AddSingleton: a single instance, which has the longest life, with the same life as Heaven. Only one instance is used in the entire application.
AddTransient: this is the most short-lived one. You may stay up late every night and die quickly. In this case, the instance of the service class is created when it is used and destroyed directly after it is used.
AddScoped: this is hard to understand. Its life cycle is within a single request, including subsequent sub-requests between the client and the server, which are cleaned up as soon as the requested session ends.
2. Injecting services
For example, instance reception is performed in middleware, on the controller, or on the constructor of other service classes (middleware is on the Invoke / InvokeAsync method).
Now let's use it and write a middleware.
Public class TestMiddleware {public TestMiddleware (RequestDelegate next) {} public Task InvokeAsync (HttpContext context, IPlayGame game) {game.Play (); return Task.CompletedTask;}}
Registered services are injected into the parameters of the InvokeAsync method. Note that the first parameter is HttpContext, which is a required parameter, followed by the injected parameter.
Finally, you can use the middleware in the Configure method of the Startup class.
Public void Configure (IApplicationBuilder app) {app.UseMiddleware ();}
After running, the Play method is called to output the following result in the console
3. Functional class
Also known as "cut off offspring" mode, do not use interface specifications, directly write functional classes.
Public class DoSomething {public string GetMessage () = > "Hello, Boss was looking for you just now." ;}
It is easier to register for the service.
Public void ConfigureServices (IServiceCollection services) {services.AddScoped ();}
The injection is done in the Configure method.
Public void Configure (IApplicationBuilder app, DoSomething thing) {Console.WriteLine (thing.GetMessage ());
After running, the output is as follows
In the container, the ServiceDescriptor class is used to store information about the service type. Where ServiceType represents the type of service, if the service has an interface and an implementation class, then this property refers to the type of the interface, and the type information of the implementation class is stored by the ImplementationType attribute. If there is no interface and only the type is defined directly, then the information for that type is stored on the ServiceType property, which is not used by the ImplementationType attribute.
In the above examples, ServiceType is the information about the IPlayGame interface, and ImplementationType is the information about the NBPlayGame class. In the case of the DoSomething class above, ServiceType is the information related to DoSomething, and ImplementationType is empty.
4. Advanced class
Next, let's look at advanced games.
Define an interface.
Public interface IDemoService {string Version {get;} void Run ();}
Then there are two classes that implement this interface.
Public class DemoService1: IDemoService {public string Version = > "v1"; public void Run () {Console.WriteLine ("the first service implementation class.") ;} public class DemoService2: IDemoService {public string Version = > "v2"; public void Run () {Console.WriteLine ("second service implementation class.") ;}}
Then we sign up for the service.
Public void ConfigureServices (IServiceCollection services) {services.AddTransient (); services.AddTransient ();}
Then, as usual, we receive the injection, and we still use the method parameters of the middleware to receive.
Public class DemoMiddleware {public DemoMiddleware (RequestDelegate next) {/ / due to program convention, this constructor must be provided. } public async Task InvokeAsync (HttpContext context, IDemoService sv) {await context.Response.WriteAsync (sv.Version);}}
The middleware is then used in the Startup.Configure method.
Public void Configure (IApplicationBuilder app, DoSomething thing) {app.UseMiddleware ();}
After running, you find a problem, look at the output.
Something goes wrong, and the parameter can only receive the last registered instance of the implementation type, that is, the DemoService2 class. So I saw that many friends posted on the Internet and asked, "does NET Core not support the injection of multiple service implementation classes?" It baffled a lot of people.
To tell you the truth, brother Core Core supports injecting multiple instances of the implementation class.
Next, Lao Zhou introduces two solutions (in fact, there are three, and one is not easy to deal with, especially if you are not familiar with brother Core, so I say two, basically enough).
Method 1. Receive the injection of IServiceProvider type.
Public async Task InvokeAsync (HttpContext context, IServiceProvider provider) {StringBuilder sb = new StringBuilder (); foreach (var sv in provider.GetServices ()) {sb.Append ($"{sv.Version}");} await context.Response.WriteAsync (sb.ToString ());}
As long as you can receive the instance referenced by IServiceProvider, you can get multiple service instances through the GetServices method.
Method 2, this method is recommended by Lao Zhou, which is simpler and injects the IEnumerable type directly, which in this case is IEnumerable.
Public async Task InvokeAsync (HttpContext context, IEnumerable svs) {StringBuilder sb = new StringBuilder (); foreach (var sv in svs) {sb.Append ($"{sv.Version}");} await context.Response.WriteAsync (sb.ToString ());}
The beauty of IEnumerable is that you can foreach, so you can access multiple instances and play with LINQ if necessary.
The running results are as follows.
The above is a sample analysis of ASP.NET Core injecting multiple service implementation classes. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to 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.