Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Service Registration with the same name in asp.net Core

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you "how to register a service of the same name in asp.net Core". The content is simple and clear. I hope it can help you solve your doubts. Let me lead you to study and learn this article "how to register a service of the same name in asp.net Core".

Usually, when using injection, a service interface corresponds to an implementation class, and the injection method can be implemented by constructor injection, but if there are multiple classes that implement the same interface, different implementation classes need to be selected according to the actual situation.

For example, both MyEmailService and EmailService in the following code implement the IEmailService interface:

Public class MyEmailService: IEmailService {public string Send (string Email) {return "My" + Email;}} public class EmailService: IEmailService return Email

In this case, you need to choose different service implementations according to different situations.

There is a container in Asp.Net Core, and you can also replace the default container with AutoFac. The following is the registration implementation of the service with the same name in two ways.

1. Use .net Core to bring your own container

If you use your own container, because our IEmailService has multiple implementation classes, you need to inject IServiceProvider, and then obtain multiple services through the plural version of GetServices of IServiceProvider. In this case, you can call multiple implementation services sequentially. If you need to distinguish one of these services, you can distinguish them by type.

[Route ("api/ [controller]")] [ApiController] public class ValuesController: ControllerBase {private readonly IEnumerable emailService; private readonly ILogger logger / injecting IServiceProvider to get services / public ValuesController (IServiceProvider serviceProvider ILogger logger) {var service = serviceProvider.GetServices () / / get service this.emailService = service; this.logger = logger } [HttpGet] public IActionResult Send (string email) / / can traverse the service foreach (var emailService in emailService) { If (emailService.GetType () = = typeof (First_EmailService)) {/ / console output call log logger.LogInformation (emailService.Send (email)) }} return Ok ();} 2, implementation in AutoFac

If you need to parse different services in Autofac, you need to use the Named implementation. First, you need to get the container of Autofac, that is, the IContainer instance. There are two kinds of locations to get:

(1) obtain it in the registration module class in ConfigureContainer. The relevant code is as follows:

Public class ConfigureAutofac: Autofac.Module {private static IContainer _ container; protected override void Load (ContainerBuilder containerBuilder) {/ / register two different named services containerBuilder.RegisterType () .Named ("one") ContainerBuilder.RegisterType () .Named ("two"); / / you need to get the container containerBuilder.RegisterBuildCallback in the call back (container = > {_ container = (IContainer) container) Var one = _ container.ResolveNamed ("two"); one.Send ("one");};}}

(2) the above services are implemented in the module configuration of Autofac or in Startup. You need to call the GetAutofacRoot method of Autofac.

/ ConfigureServices injects the default container, and Autofac replaces the default Then execute ConfigureContainer / public void ConfigureContainer (ContainerBuilder builder) {builder.RegisterType () .As () } / / Register the root container public ILifetimeScope AutofacContainer {get; private set;} public void Configure (IApplicationBuilder app, IWebHostEnvironment env) this.AutofacContainer = app.ApplicationServices.GetAutofacRoot () Var serviceName = this.AutofacContainer.Resolve (); serviceName.ShowCode (); / /.

(3) if you need to implement service invocation with different names in the controller, you need to inject IApplicationBuilder interface into the controller, but direct injection will report an error that the service is not resolved, and you need to manually configure it in ConfigureServices.

Services.AddSingleton ()

Then it can be injected into the controller normally.

[Route ("api/ [controller]")] [ApiController] public class ValuesController: ControllerBase {private readonly IApplicationBuilder app; private readonly ILogger logger; public ILifetimeScope AutofacContainer {get; private set } public ValuesController (IApplicationBuilder app, ILogger logger) {this.app = app; this.logger = logger } [HttpGet] public IActionResult Send (string email) this.AutofacContainer = app.ApplicationServices.GetAutofacRoot (); var serviceName = this.AutofacContainer.ResolveNamed ("one") Logger.LogInformation (serviceName.Send (string.Empty)); return Ok ();} these are all the contents of the article "how to register a service with the same name in asp.net Core". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report