c# - 如何使用 Simple Injector 有条件地注册一个集合?

标签 c# dependency-injection simple-injector

我正在尝试在 Simple Injector 中注册以下组合:

  1. IMyInterface 的(一个或多个)实现集合对于具体类型,例如Implementation1<MyClass>Implementation2<MyClass>对于 IMyInterface<MyClass>
  2. 开放通用 类型的虚拟集合(空列表)IMyInterface<T>作为后备(有条件的?)

这样我想确保所有 IEnumerable<IMyInterface<T>> 的请求者将至少得到一个空列表或实际实现列表; IEnumerable<IMyInterface<MyClass>> 的请求者应该得到具有元素 List<IMyInterface<MyClass>> 的可枚举实例(例如 Implementation1<MyClass>)和 Implementation2<MyClass> , 以及 IEnumerable<IMyInterface<AnotherClass>> 的请求者应该得到 Enumerable.Empty<IMyInterface<AnotherClass>> .

类列表在注册码中不固定。我已经实现了一个 Bootstrap ,从程序集中收集所有实现。

我尝试使用 RegisterCollection 的几种组合和 RegisterConditional ,但没有人满足所有要求。 是否有(不存在的)RegisterCollectionConditional 的解决方法?

最佳答案

更新了 v4.3 语法。

你想做的事情不需要在 Simple Injector 中做任何特殊的事情; Simple Injector 将自动为您选择任何可分配的类型。假设有以下类型:

class Implementation1 : IMyInterface<MyClass> { }
class Implementation2 : IMyInterface<MyClass> { }
class Implementation3 : IMyInterface<FooBarClass>, IMyInterface<MyClass> { }

注册看起来如下:

container.Collection.Register(typeof(IMyInterface<>),
    typeof(Implementation1),
    typeof(Implementation2),
    typeof(Implementation3));

这将导致以下结果:

// returns: Implementation1, Implementation2, Implementation3.
container.GetAllInstances<IMyInterface<MyClass>>();

// returns: Implementation3.
container.GetAllInstances<IMyInterface<FooBarClass>>();


// returns: empty list.
container.GetAllInstances<IMyInterface<AnotherClass>>();

除了手动注册所有类型,您还可以使用批量注册:

container.Collection.Register(typeof(IMyInterface<>),
    typeof(Implementation1).Assembly);

这将注册所有实现(假设它们都在同一个程序集中)。

如果您有以下类型:

class Implementation1<T> : IMyInterface<T> { }
class Implementation2<T> : IMyInterface<T> { }
class Implementation3<T> : IMyInterface<T> { }

您可以进行以下注册:

container.Collection.Register(typeof(IMyInterface<>),
    typeof(Implementation1<MyClass>),
    typeof(Implementation2<MyClass>),
    typeof(Implementation3<MyClass>),
    typeof(Implementation3<FooBarClass>));

此注册将产生与我们之前看到的相同的结果:

// returns: Implementation1<MyClass>, Implementation2<MyClass>, Implementation3<MyClass>.
container.GetAllInstances<IMyInterface<MyClass>>();

// returns: Implementation3<FooBarClass>.
container.GetAllInstances<IMyInterface<FooBarClass>>();

// returns: empty list.
container.GetAllInstances<IMyInterface<AnotherClass>>();

有关详细信息,请参阅 collections sectiongeneric collections section在文档中。

关于c# - 如何使用 Simple Injector 有条件地注册一个集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39898546/

相关文章:

scala - Cake Pattern 可以用于非单例样式的依赖吗?

c# - 简易喷油器 : Injecting a property in a base class

c# - 使用SimpleInjector基于泛型参数条件注册装饰器

c# - 逐步构建 OR 查询表达式

java - ANTLR 4 - 支持空格和特殊字符的字符串语法规则

javascript - 无法使用 Jquery 3.4.1、c# mvc 设置下拉列表的选定属性

c# - 在 Web API 和 OWIN 中使用简单注入(inject)器

c# - 如何获取使用 System.Diagnostics.Process.GetProcess(string) 的权限?

c# - 我可以在 Controller 的构造函数中访问 User.Identity.Name 吗?如果不是,最佳实践是什么?

azure - .net 7 隔离的 Azure 函数依赖注入(inject)在部署时失败(在本地工作)