[英]Registering instances of same type with Simple Injector
I have just picked up Simple Injector and all I currently want to do is this: 我刚拿起Simple Injector,我目前想做的就是:
Container.Register<IMessageHandler>(() => new MessageHandlerOne());
Container.Register<IMessageHandler>(() => new MessageHandlerTwo());
I'm just trying to register two message handlers, so I can later iterate through them. 我只是想注册两个消息处理程序,所以我可以稍后迭代它们。
To get back these registered instances, this method sounds like it would do the trick. 要恢复这些注册的实例,这种方法听起来就像它可以做到的那样。
var instances = Container.GetAllInstances<IMessageHandler>();
//why doesn't instances contain both MessageHandlerOne, and MessageHandlerTwo ?
Instead this returns back an empty IEnumerable
. 而是返回一个空的IEnumerable
。
What am I doing wrong? 我究竟做错了什么? For something named Simple Injector you would think this would work? 对于名为Simple Injector的东西,您会认为这会起作用吗? Am I thinking about this the wrong way? 我是否以错误的方式思考这个问题?
What you are trying to do should fail with an exception on the second call to Container.Register<IMessageHandler>
since the Simple Injector API clearly differentiates the registration of collections . 您尝试做的事情应该在第二次调用Container.Register<IMessageHandler>
失败,因为Simple Injector API 明确区分了集合的注册 。
In other words, if you want to resolve a collection, you should register a collection: 换句话说,如果要解析集合,则应注册集合:
Container.Collection.Register<IMessageHandler>(
typeof(MessageHandlerOne),
typeof(MessageHandlerTwo));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.