simpleinjector 3.0 不支持 RegisterManyForOpenGeneric

simpleinjector 3.0 not supporting RegisterManyForOpenGeneric

所以我决定将我的 simpleinjector 版本升级到 3.0,突然我收到一条消息:

'SimpleInjector.Extensions.OpenGenericBatchRegistrationExtensions.RegisterManyForOpenGeneric(SimpleInjector.Container, System.Type, params System.Reflection.Assembly[])' is obsolete: 'This extension method has been removed. Please use Container.Register(Type, IEnumerable) instead.

文档中仍然有这个方法:

http://simpleinjector.readthedocs.org/en/latest/advanced.html

所以我很好奇,有什么替代方案:

container.RegisterManyForOpenGeneric(typeof(IEventHandler<>),
                                     container.RegisterAll,
                                     typeof(IEventHandler<>).Assembly);

啊..挠了几个小时的脑袋,我想通了:

container.RegisterCollection(typeof(IEventHandler<>),
                             typeof(IEventHandler<>).Assembly);

RegisterCollection 也处理开放泛型。也许这应该记录在某处。

编辑:

我在新文档中发现,上面的代码不是RegisterManyForOpenGeneric的直接翻译。它所做的只是解决了我的编译,但它没有注册我的处理程序,我今天刚检查过。

Additional information: No registration for type

这是正确的版本:

container.Register(typeof(IEventHandler<>),
                   new[] { typeof(IEventHandler<>).Assembly });

使用 RegisterCollection 需要一些额外的代码更改(来自文档):

Because we register a collection, we can no longer call container.GetInstance>(). Instead instances can be retrieved by having an IEnumerable> constructor argument or by calling container.GetAllInstances>().

我没有做过,也不需要做,因为我没有混合使用开放泛型和非泛型。但如果我想改进我的项目,我会在未来更多地探索这一点。