Register and analyze multiple interfaces in ASP.NET CORE to implement
When using the same interface services, they may be a challenge based on unique key registration and analysis. Unlike other IOC containers that are allowed to distinguish the specific implementation, the default DI system of ASP.NET CORE seems to be limited in this regard.
Solution: Use FUNC to commission
In order to overcome this limit, it can be achieved by using the type sharing commission as a variable -pass scheme. The entrusted key uses the key as a parameter and returns an instance of the required service.
ServiceResolver
In the file, use the
<code class="language-csharp">public delegate IService ServiceResolver(string key);</code>
Startup.cs
In any class injected by DI, you can use ServiceResolver
to obtain the required service:
<code class="language-csharp">services.AddTransient<ServiceA>(); services.AddTransient<ServiceB>(); services.AddTransient<ServiceC>(); services.AddTransient<ServiceResolver>(serviceProvider => key => { switch (key) { case "A": return serviceProvider.GetService<ServiceA>(); case "B": return serviceProvider.GetService<ServiceB>(); case "C": return serviceProvider.GetService<ServiceC>(); default: throw new KeyNotFoundException(); } });</code>
Note: ServiceResolver
This method uses the string key for simplifying the purpose, but if necessary, you can use any custom parsing type as the key.
<code class="language-csharp">public class Consumer { private readonly IService _aService; public Consumer(ServiceResolver serviceAccessor) { _aService = serviceAccessor("A"); } public void UseServiceA() { _aService.DoTheThing(); } }</code>
Although this solution solves the problem of key betting and analyzing multiple interface implementation, it is necessary to pay attention to the following points:
This solution involves manual mapping. If it is not maintained properly, it may be easy to make mistakes.
It does not solve the problem of injecting static data into the constructor during the registration period. For this reason, consider using option mode or other technologies.
The above is the detailed content of How Can I Register and Resolve Multiple Interface Implementations with Unique Keys in ASP.NET Core Dependency Injection?. For more information, please follow other related articles on the PHP Chinese website!