[英]Simple Injector 3 does not return general instances
I am using Simple Injector and just updated from v2 to v3. 我正在使用简单注入器,并且刚刚从v2更新到v3。 I am using the DI container to resolve associated event handlers to an event. 我正在使用DI容器将关联的事件处理程序解析为一个事件。
All EventHandlers implement the interface IDomainEventHandler
and all events implement IDomainEvent
. 所有的事件处理器实现接口IDomainEventHandler
和所有事件实施IDomainEvent
。
The EventHandlers are registered: EventHandlers已注册:
container.Register(typeof(IDomainEventHandler<>),
new[] { typeof(IDomainEventHandler).Assembly });
I collect all handlers to a certain event like so: 我将所有处理程序收集到某个事件中,如下所示:
public void Dispatch<TDomainEvent>(TDomainEvent domainEvent)
where TDomainEvent : IDomainEvent
{
var eventHandlers =
_dependencyResolver.GetAllInstances<IDomainEventHandler<TDomainEvent>>();
foreach (var domainEventHandler in eventHandlers)
domainEventHandler.Handle(domainEvent);
}
I have a general event handler, which handles all events who implements IDomainEvent
interface. 我有一个通用的事件处理程序,它处理实现IDomainEvent
接口的所有事件。 It is defined like this: 定义如下:
public class EventStoreDomainEventHandler : IDomainEventHandler<IDomainEvent>
{
public void Handle(IDomainEvent domainEvent)
{ ... }
}
When I try to get all instances from the DI container of a certain event which implements the IDomainEvent
interface, I don't receive an instance of the EventStoreDomainEventhandler
. 当我尝试从实现IDomainEvent
接口的某个事件的DI容器中获取所有实例时,我没有收到EventStoreDomainEventhandler
的实例。
Is there a way to register and get all handlers of a type, and also all handlers associated to interfaces implemented by the type? 有没有一种方法可以注册和获取某个类型的所有处理程序,以及与该类型实现的接口关联的所有处理程序?
Hope it makes sense :o) 希望有道理:o)
Kind Regards Frederik 亲切的问候弗雷德里克
This happens because Simple Injector separates registration of collections from one-to-one mappings , while you are registering your handlers with Register
, while you are resolving them with GetAllInstances
. 发生这种情况是因为,当您使用Register
来注册处理程序时,而使用GetAllInstances
来解决它们时, GetAllInstances
集合的注册与一对一映射 GetAllInstances
。 You should either use the following combination: 您应该使用以下组合:
container.Register(typeof(IDomainEventHandler<>), assemblies);
_dependencyResolver.GetInstance<IDomainEventHandler<TDomainEvent>>();
or: 要么:
// NOTE: v4.3+ syntax
container.Collection.Register(typeof(IDomainEventHandler<>), assemblies);
_dependencyResolver.GetAllInstances<IDomainEventHandler<TDomainEvent>>();
You need to explicitly state the variance in within your interface definition 您需要明确说明方差在接口定义中
public interface IDomainEventHandler<in TDomainEvent> { }
marking the interface with in and out keywords communicates that covariance and contravariance is expected and there could therefore be multiple applicable implementations 用in和out关键字标记接口可表明期望有协方差和自变量,因此可能有多个适用的实现
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.