How to register multiple implementations of the same interface in Asp.Net Core?

前端 未结 24 1950
不思量自难忘°
不思量自难忘° 2020-11-22 10:16

I have services that are derived from the same interface.

public interface IService { }
public class ServiceA : IService { }
public class ServiceB : IService         


        
24条回答
  •  难免孤独
    2020-11-22 11:03

    A factory approach is certainly viable. Another approach is to use inheritance to create individual interfaces that inherit from IService, implement the inherited interfaces in your IService implementations, and register the inherited interfaces rather than the base. Whether adding an inheritance hierarchy or factories is the "right" pattern all depends on who you speak to. I often have to use this pattern when dealing with multiple database providers in the same application that uses a generic, such as IRepository, as the foundation for data access.

    Example interfaces and implementations:

    public interface IService 
    {
    }
    
    public interface IServiceA: IService
    {}
    
    public interface IServiceB: IService
    {}
    
    public IServiceC: IService
    {}
    
    public class ServiceA: IServiceA 
    {}
    
    public class ServiceB: IServiceB
    {}
    
    public class ServiceC: IServiceC
    {}
    

    Container:

    container.Register();
    container.Register();
    container.Register();
    

提交回复
热议问题