如何使用Simple Injector有条件地注册集合?

时间:2016-10-06 14:22:04

标签: c# dependency-injection simple-injector

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

  1. 针对具体类型的IMyInterface的(一个或多个)实现的集合,例如Implementation1<MyClass>
  2. Implementation2<MyClass>IMyInterface<MyClass>
  3. 开放通用类型IMyInterface<T>的虚拟集合(空列表)作为后备(有条件的?)
  4. 这样我想确保IEnumerable<IMyInterface<T>>的所有请求者至少获得一个空列表或实际实现列表; IEnumerable<IMyInterface<MyClass>>的请求者应该获得包含元素List<IMyInterface<MyClass>>Implementation1<MyClass>的可枚举实例(例如Implementation2<MyClass>),IEnumerable<IMyInterface<AnotherClass>>的请求者应该获得Enumerable.Empty<IMyInterface<AnotherClass>>

    注册码中未修复类列表。我已经实现了一个从程序集收集所有实现的引导程序。

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

1 个答案:

答案 0 :(得分:1)

使用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

相关问题