Solve multiple registered registrations in ASP.NET CORE
ASP.NET CORE itself does not support the implementation of the same interface that can be distinguished by the key distinction. To overcome this limit, developers depend on alternative methods, such as factory models. However, these solutions will lead to increased dependence and may violate the principle of inversion of dependence (DIP).
The more effective solution is to use the shared commission
to map the key value to the specific implementation. The following is a specific step:
ServiceResolver
Define a commission for service analysis.
IService ServiceResolver(string key)
Service registration:
The mapping of the type to the type: Startup.cs
<code class="language-csharp">services.AddTransient<ServiceA>(); services.AddTransient<ServiceB>(); services.AddTransient<ServiceC>();</code>
Service use:
ServiceResolver
Inject into the class that needs to be registered. For example:
<code class="language-csharp">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>
This method provides a flexible way to register and analyze multiple implementation of the same interface, so as to achieve more effective dependency management and abide by DIP. Although it is not the built -in function of ASP.NET CORE, it provides a feasible solution for the common DI challenge.
The above is the detailed content of How to Resolve Multiple Implementations of the Same Interface in ASP.NET Core?. For more information, please follow other related articles on the PHP Chinese website!