基于泛型解析抽象class

Resolve abstract class based on generics

我想使用 Unity 解析抽象 class。 抽象 class 具有具有某些泛型的实现。例如:

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

public class face : Iface<SomeClassExample, OtherClassExample>

那我要执行:

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

但它给出了错误异常是:

InvalidOperationException - Instances of abstract classes cannot be created.

这很明显,因为我想创建一个摘要 class。我希望 Unity 足够聪明,能够根据泛型找到特定的 class。有可能做这样的事情吗?

您需要明确要求它解析您的 face class。仅查看错误消息,它正在尝试创建 Iface<SomeClassExample, OtherClassExample>

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

如果你想使用Iface作为界面——创建一个界面并注册它

您需要显式注册面部 class 并使用正确的泛型映射它。

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

尽管如此,我相信 Unity 应该可以自动识别属于某些泛型的正确 class...

编辑: 其实有办法!

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

它会自动注册所有实现此基础 class 的通用派生 classes class。