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

前端 未结 24 1980
不思量自难忘°
不思量自难忘° 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 10:48

    Most of the answers here violate the single responsibility principle (a service class should not resolve dependencies itself) and/or use the service locator anti-pattern.

    Another option to avoid these problems is to:

    • use an additional generic type parameter on the interface or a new interface implementing the non generic interface,
    • implement an adapter/interceptor class to add the marker type and then
    • use the generic type as “name”

    I’ve written an article with more details: Dependency Injection in .NET: A way to work around missing named registrations

提交回复
热议问题