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>();
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>();