Home > Backend Development > C++ > How to Resolve Multiple Implementations of the Same Interface in ASP.NET Core?

How to Resolve Multiple Implementations of the Same Interface in ASP.NET Core?

DDD
Release: 2025-01-29 21:11:10
Original
860 people have browsed it

How to Resolve Multiple Implementations of the Same Interface in ASP.NET Core?

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

Entrusted statement:
  1. Define a commission for service analysis.

    IService ServiceResolver(string key) Service registration:

  2. In , each specific implementation is registered as a transient service:

    The mapping of the type to the type: Startup.cs

    <code class="language-csharp">services.AddTransient<ServiceA>();
    services.AddTransient<ServiceB>();
    services.AddTransient<ServiceC>();</code>
    Copy after login
    Configure Entrust the key value to the specific implementation:
  3. 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>
    Copy after login
  4. 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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template