2017-02-06 138 views
2

我想使用Unity来解析抽象类。 抽象类具有某些泛型的实现。例如:解决基于泛型的抽象类

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

public class face : Iface<SomeClassExample, OtherClassExample> 

然后我想执行:

UnityContainer.Resolve<Iface<SomeClassExample, OtherClassExample>>(); 

但它给出了错误的例外是:

出现InvalidOperationException - 抽象类的实例不能被创建。

这是显而易见的,因为我想创建一个抽象类。我希望Unity能够聪明地找到基于泛型的特定课程。是可以做这样的事情吗?

+3

统一是一个依赖注入容器,而不是一个神奇的灯。例如通过反射注册实现。 – Dbl

+0

是的,你需要在Unity中注册'face',并在每次代码请求'Iface 时告诉它使用'face'。 – Brandon

+0

如果你需要注册face,那么在这里使用反射有什么意义?我不妨称呼新面孔(); – Wouter

回答

0

你需要明确注册脸类并将其映射为正确的泛型。

UnityContainer.RegisterType<Iface<SomeClassExample, OtherClassExample>, face>(); 

即使这样,我相信它应该是可能的团结识别属于自动某些仿制药的正确类...

编辑: 有实际上是一个办法!

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

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

0

您需要明确要求它解决您的face类。只看该错误消息,它试图创建的Iface<SomeClassExample, OtherClassExample>

UnityContainer.Resolve<face<SomeClassExample, OtherClassExample>>(); 

一个实例。如果你想使用IFACE作为接口—创建一个接口,并将其注册