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

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

    since my post above, I have moved to a Generic Factory Class

    Usage

     services.AddFactory()
             .Add("A")
             .Add("B");
    
     public MyClass(IFactory processorFactory)
     {
           var x = "A"; //some runtime variable to select which object to create
           var processor = processorFactory.Create(x);
     }
    

    Implementation

    public class FactoryBuilder where I : class
    {
        private readonly IServiceCollection _services;
        private readonly FactoryTypes _factoryTypes;
        public FactoryBuilder(IServiceCollection services)
        {
            _services = services;
            _factoryTypes = new FactoryTypes();
        }
        public FactoryBuilder Add(P p)
            where T : class, I
        {
            _factoryTypes.ServiceList.Add(p, typeof(T));
    
            _services.AddSingleton(_factoryTypes);
            _services.AddTransient();
            return this;
        }
    }
    public class FactoryTypes where I : class
    {
        public Dictionary ServiceList { get; set; } = new Dictionary();
    }
    
    public interface IFactory
    {
        I Create(P p);
    }
    
    public class Factory : IFactory where I : class
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly FactoryTypes _factoryTypes;
        public Factory(IServiceProvider serviceProvider, FactoryTypes factoryTypes)
        {
            _serviceProvider = serviceProvider;
            _factoryTypes = factoryTypes;
        }
    
        public I Create(P p)
        {
            return (I)_serviceProvider.GetService(_factoryTypes.ServiceList[p]);
        }
    }
    

    Extension

    namespace Microsoft.Extensions.DependencyInjection
    {
        public static class DependencyExtensions
        {
            public static IServiceCollection AddFactory(this IServiceCollection services, Action> builder)
                where I : class
            {
                services.AddTransient, Factory>();
                var factoryBuilder = new FactoryBuilder(services);
                builder(factoryBuilder);
                return services;
            }
        }
    }
    

提交回复
热议问题