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

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

    I have run into the same problem and I worked with a simple extension to allow Named services. You can find it here:

    • https://www.nuget.org/packages/Subgurim.Microsoft.Extensions.DependencyInjection.Named/
    • https://github.com/subgurim/Microsoft.Extensions.DependencyInjection.Named

    It allows you to add as many (named) services as you want like this:

     var serviceCollection = new ServiceCollection();
     serviceCollection.Add(typeof(IMyService), typeof(MyServiceA), "A", ServiceLifetime.Transient);
     serviceCollection.Add(typeof(IMyService), typeof(MyServiceB), "B", ServiceLifetime.Transient);
    
     var serviceProvider = serviceCollection.BuildServiceProvider();
    
     var myServiceA = serviceProvider.GetService("A");
     var myServiceB = serviceProvider.GetService("B");
    

    The library also allows you to easy implement a "factory pattern" like this:

        [Test]
        public void FactoryPatternTest()
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection.Add(typeof(IMyService), typeof(MyServiceA), MyEnum.A.GetName(), ServiceLifetime.Transient);
            serviceCollection.Add(typeof(IMyService), typeof(MyServiceB), MyEnum.B.GetName(), ServiceLifetime.Transient);
    
            serviceCollection.AddTransient();
    
            var serviceProvider = serviceCollection.BuildServiceProvider();
    
            var factoryPatternResolver = serviceProvider.GetService();
    
            var myServiceA = factoryPatternResolver.Resolve(MyEnum.A);
            Assert.NotNull(myServiceA);
            Assert.IsInstanceOf(myServiceA);
    
            var myServiceB = factoryPatternResolver.Resolve(MyEnum.B);
            Assert.NotNull(myServiceB);
            Assert.IsInstanceOf(myServiceB);
        }
    
        public interface IMyServiceFactoryPatternResolver : IFactoryPatternResolver
        {
        }
    
        public class MyServiceFactoryPatternResolver : FactoryPatternResolver, IMyServiceFactoryPatternResolver
        {
            public MyServiceFactoryPatternResolver(IServiceProvider serviceProvider)
            : base(serviceProvider)
            {
            }
        }
    
        public enum MyEnum
        {
            A = 1,
            B = 2
        }
    

    Hope it helps

提交回复
热议问题