C# 基于泛型解析抽象类

C# 基于泛型解析抽象类,c#,generics,unity-container,C#,Generics,Unity Container,我想使用Unity解析一个抽象类。 抽象类具有具有特定泛型的实现。例如: public abstract class Iface<S, T> where S : SomeClass where T : OtherClass public class face : Iface<SomeClassExample, OtherClassExample> 公共抽象类Iface其中S:SomeClass其中T:OtherClass 公共类面孔:Iface 然后我想执行: Un

我想使用Unity解析一个抽象类。 抽象类具有具有特定泛型的实现。例如:

public abstract class Iface<S, T> where S : SomeClass where T : OtherClass

public class face : Iface<SomeClassExample, OtherClassExample>
公共抽象类Iface其中S:SomeClass其中T:OtherClass
公共类面孔:Iface
然后我想执行:

UnityContainer.Resolve<Iface<SomeClassExample, OtherClassExample>>();
UnityContainer.Resolve();
但它给出的错误例外是:

InvalidOperationException-无法创建抽象类的实例


这很明显,因为我想创建一个抽象类。我希望Unity足够聪明,能够找到基于泛型的特定类。可以这样做吗?

您需要明确要求它解析到您的
类。仅查看错误消息,它正在尝试创建
Iface的实例

UnityContainer.Resolve();

如果要将Iface用作接口-创建一个接口并注册它

,则需要显式注册face类并将其映射到正确的泛型

UnityContainer.RegisterType<Iface<SomeClassExample, OtherClassExample>, face>();
UnityContainer.RegisterType();
尽管如此,我相信Unity应该能够自动识别属于某些泛型的正确类

编辑: 其实是有办法的

UnityContainer.ConfigureAutoRegistration().Include(type => type.ImplementsOpenGeneric(typeof(Iface<,>)), Then.Register().AsFirstInterfaceOfType()).ApplyAutoRegistration();
UnityContainer.ConfigureAutoRegistration().Include(type=>type.implementsPengeneric(typeof(Iface)),然后.Register().asfirstInterfaceOftType()).ApplyAutoRegistration();

它会自动注册实现该基类的所有泛型派生类。

unity是一个依赖项注入容器,而不是一个幻灯。例如,通过反射注册实现。是的,您需要使用Unity注册
face
,并告诉它在代码要求
Iface
时使用
face
如果您需要注册face,那么在这里使用反射有什么意义?我不妨称之为新面孔()@很明显,你正在使用DI,但还不了解它-这是可以的。这不是一个容易的话题。区别在于,您应该使用接口而不是具体的实现,而您的测试环境+生产环境有单独的注册例程。因此,使用Resolve()是执行DI的正确方法。谷歌“按约定注册DI unity”以查看指南。有很多DI容器提供了一套非常不同的注册功能。@Dbl感谢您的回复。你说得对。
UnityContainer.ConfigureAutoRegistration().Include(type => type.ImplementsOpenGeneric(typeof(Iface<,>)), Then.Register().AsFirstInterfaceOfType()).ApplyAutoRegistration();