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

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

    After reading the answers here and articles elsewhere I was able to get it working without strings. When you have multiple implementations of the same interface the DI will add these to a collection, so it's then possible to retrieve the version you want from the collection using typeof.

    // In Startup.cs
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped(IService, ServiceA);
        services.AddScoped(IService, ServiceB);
        services.AddScoped(IService, ServiceC);
    }
    
    // Any class that uses the service(s)
    public class Consumer
    {
        private readonly IEnumerable _myServices;
    
        public Consumer(IEnumerable myServices)
        {
            _myServices = myServices;
        }
    
        public UseServiceA()
        {
            var serviceA = _myServices.FirstOrDefault(t => t.GetType() == typeof(ServiceA));
            serviceA.DoTheThing();
        }
    
        public UseServiceB()
        {
            var serviceB = _myServices.FirstOrDefault(t => t.GetType() == typeof(ServiceB));
            serviceB.DoTheThing();
        }
    
        public UseServiceC()
        {
            var serviceC = _myServices.FirstOrDefault(t => t.GetType() == typeof(ServiceC));
            serviceC.DoTheThing();
        }
    }
    

提交回复
热议问题