依赖注入:注入泛型接口的 IEnumerable<I<Base>>

问题描述 投票:0回答:1
我想注入通用接口的

IEnumerable

。
使用
Microsoft.Extensions.DependencyInjection
可以实现吗?

这对于协变和逆变都不起作用。零实现被注入到

ConcreteClassFactory

。有什么办法可以做到吗?

public interface IGenericInterface<T> { void Do(T obj); } public abstract class Animal { } public class Dog : Animal { } public class Cat : Animal { } public class ConcreteClassA : IGenericInterface<Dog> { public void Do(Dog obj) { throw new NotImplementedException(); } } public class ConcreteClassB : IGenericInterface<Cat> { public void Do(Cat obj) { throw new NotImplementedException(); } } public class ConcreteClassFactory { public ConcreteClassFactory(IEnumerable<IGenericInterface<Animal>> concretes) { } }
服务注册:

builder.Services .AddSingleton<IGenericInterface<Cat>, ConcreteClassB>() .AddSingleton<IGenericInterface<Dog>, ConcreteClassA>() .AddSingleton<ConcreteClassFactory>();
    
c# .net asp.net-core dependency-injection microsoft-extensions-di
1个回答
0
投票
是的,通过依赖注入,您可以创建一个两个泛型接口都可以实现的非泛型接口:

public interface IGenericInterface<T> { void Do(T obj); } public interface INonGenericInterface { void Do(object obj); } // your three Animal classes public class ConcreteClassA : IGenericInterface<Dog>, INonGenericInterface { public void Do(Dog obj) { throw new NotImplementedException(); } public void Do(object obj) { Do((Dog)obj); } } public class ConcreteClassB : IGenericInterface<Cat>, INonGenericInterface { public void Do(Cat obj) { throw new NotImplementedException(); } public void Do(object obj) { Do((Cat)obj); } } public class ConcreteClassFactory { public ConcreteClassFactory(IEnumerable<INonGenericInterface> concretes) { foreach (var concrete in concretes) { // Perform initialization or registration } } }
服务注册:

builder.Services .AddSingleton<IGenericInterface<Cat>, ConcreteClassB>() .AddSingleton<IGenericInterface<Dog>, ConcreteClassA>() .AddSingleton<INonGenericInterface, ConcreteClassB>() .AddSingleton<INonGenericInterface, ConcreteClassA>() .AddSingleton<ConcreteClassFactory>();
    
© www.soinside.com 2019 - 2024. All rights reserved.