简单的注射器后备注册

时间:2014-08-07 18:29:22

标签: c# dependency-injection simple-injector

我在文档中读到,可以为未处理的类型创建后备注册,但我似乎无法再查找该页面了。无论如何,假设我理解后备注册,我的问题很简单。

我想设置容器,以便在无法找到NullCommandHandler<T> : ICommandHandler<T>服务类型的注册时实例化ICommandHandler<T>类型。这可能吗?

1 个答案:

答案 0 :(得分:1)

这很简单,你只需使用RegisterOpenGeneric。此方法使用未注册的类型解析,这意味着它只在没有注册时被拾取。所以使用命令处理程序,它看起来像这样:

// Register all implementations of ICommandHandler<T>
container.RegisterManyForOpenGeneric(
    typeof(ICommandHandler<>),
    AppDomain.CurrentDomain.GetAssemblies());

container.RegisterOpenGeneric(
    typeof(ICommandHandler<>),
    typeof(NullCommandHandler<>),
    Lifestyle.Singleton);
您正在搜索的

Here is the documentation