Simple Injector 3 没有 return 个一般实例

Simple Injector 3 does not return general instances

我正在使用 Simple Injector 并且刚刚从 v2 更新到 v3。 我正在使用 DI 容器将关联的事件处理程序解析为事件。

所有事件处理程序都实现接口 IDomainEventHandler,所有事件都实现 IDomainEvent

事件处理程序已注册:

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)

亲切的问候 弗雷德里克

发生这种情况是因为简单注入器 separates registration of collections from one-to-one mappings,当您使用 Register 注册您的处理程序时,当您使用 GetAllInstances 解析它们时。您应该使用以下组合:

container.Register(typeof(IDomainEventHandler<>), assemblies);

_dependencyResolver.GetInstance<IDomainEventHandler<TDomainEvent>>();

或:

// NOTE: v4.3+ syntax
container.Collection.Register(typeof(IDomainEventHandler<>), assemblies);

_dependencyResolver.GetAllInstances<IDomainEventHandler<TDomainEvent>>();

您需要在接口定义中中明确说明差异

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

有关详细信息,请参阅 here