简体   繁体   English

使用Simple Injector注册相同类型的实例

[英]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.

相关问题 在 Simple Injector 中使用名称注册两个相同服务类型的不同实例 - Registering two different istances of the same service type with a name in Simple Injector Simple Injector可以使用不同的构造函数参数注册相同类型的多个实例吗? - Can Simple Injector register multiple instances of same type using different constructor parameters? 在 Simple Injector 中注册一个具体类型并使用它会抛出 ActivationException - Registering a concrete type in Simple Injector and using it throws ActivationException Simple Injector:使用基于其父级的构造函数参数注册类型 - Simple Injector: Registering a type with constructor argument that's based on its parent Simple Injector:使用构造函数参数注册开放通用类型 - Simple Injector: Registering open generic type with constructor parameter 在 Simple Injector 中注册具有多个构造函数和字符串依赖项的类型 - Registering a type with multiple constructors and string dependency in Simple Injector 简单的注入器注册动态类型 - Simple Injector registering dynamic types 使用Simple Injector 3.1.2注册IUserStore - Registering IUserStore with Simple Injector 3.1.2 简单注入器 - 注册 ASP.NET 身份 - Simple Injector - Registering ASP.NET Identity 在简单注入器中手动注册Web API控制器 - Manually registering web api controllers in simple injector
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM