simpleinjector 3.0 not supporting RegisterManyForOpenGeneric

本文关键字:supporting RegisterManyForOpenGeneric not simpleinjector | 更新日期: 2023-09-27 18:08:31

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

' SimpleInjector.Extensions.OpenGenericBatchRegistrationExtensions.RegisterManyForOpenGeneric (SimpleInjector。容器,系统。类型,参数System.Reflection.Assembly[])'已过时:'此扩展方法已被删除。请使用容器。Register(Type, IEnumerable)

文档中仍然有这个方法:

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

我很好奇,有什么可以替代

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

simpleinjector 3.0 not supporting RegisterManyForOpenGeneric

啊…挠头了几个小时后,我终于明白了:

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

RegisterCollection也处理开放泛型。也许这应该在某个地方记录下来。

编辑:

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

Additional information: No registration for type

这是正确的版本:

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

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

因为注册了一个集合,所以不能再调用container.GetInstance>()。相反,实例可以通过IEnumerable>构造函数参数或调用container.GetAllInstances>()来检索。

我没有这样做,也不需要这样做,因为我没有混合开放泛型和非泛型。但是如果我以后想要修改我的项目的话,我会进一步研究这个