我正在尝试在 Simple Injector 中注册以下组合:
IMyInterface
的(一个或多个)实现集合对于具体类型,例如Implementation1<MyClass>
和Implementation2<MyClass>
对于IMyInterface<MyClass>
- 开放通用 类型的虚拟集合(空列表)
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 section和 generic collections section在文档中。
关于c# - 如何使用 Simple Injector 有条件地注册一个集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39898546/