我正在使用简单注入器,并且刚刚从v2更新到v3。
我正在使用DI容器将关联的事件处理程序解析为一个事件。
所有EventHandlers实现接口IDomainEventHandler
,所有事件实现IDomainEvent
。
EventHandlers已注册:
container.Register(typeof(IDomainEventHandler<>),
new[] { typeof(IDomainEventHandler).Assembly });
我将所有处理程序收集到某个事件中,如下所示:
public void Dispatch<TDomainEvent>(TDomainEvent domainEvent)
where TDomainEvent : IDomainEvent
{
var eventHandlers =
_dependencyResolver.GetAllInstances<IDomainEventHandler<TDomainEvent>>();
foreach (var domainEventHandler in eventHandlers)
domainEventHandler.Handle(domainEvent);
}
我有一个通用的事件处理程序,它处理实现
IDomainEvent
接口的所有事件。定义如下:public class EventStoreDomainEventHandler : IDomainEventHandler<IDomainEvent>
{
public void Handle(IDomainEvent domainEvent)
{ ... }
}
当我尝试从实现
IDomainEvent
接口的某个事件的DI容器中获取所有实例时,我没有收到EventStoreDomainEventhandler
的实例。有没有一种方法可以注册和获取某个类型的所有处理程序,以及与该类型实现的接口关联的所有处理程序?
希望有道理:o)
亲切的问候
弗雷德里克
最佳答案
发生这种情况的原因是,当您使用Register
注册处理程序时,而使用GetAllInstances
解析处理程序时,简单注入器separates registration of collections from one-to-one mappings。您应该使用以下组合:
container.Register(typeof(IDomainEventHandler<>), assemblies);
_dependencyResolver.GetInstance<IDomainEventHandler<TDomainEvent>>();
要么:
// NOTE: v4.3+ syntax
container.Collection.Register(typeof(IDomainEventHandler<>), assemblies);
_dependencyResolver.GetAllInstances<IDomainEventHandler<TDomainEvent>>();
关于c# - Simple Injector 3不返回一般实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32112779/