SimpleInjector.GetAllInstances 抛出意外错误

SimpleInjector.GetAllInstances throwing unexpected error

我有以下引发域事件的方法。 IDomainEvent 的实例被传递给该方法,并使用由 SimpleInjector 的 GetAllInstances 方法提供的 IDomainEventHandler 实例进行处理。

该方法如下所示:

public static void Raise<T>(T domainEvent) where T : IDomainEvent
{
    if (Container != null)
    {
        var handlerType =
            typeof(IDomainEventHandler<>).MakeGenericType(domainEvent.GetType());

        var handlers = Container.GetAllInstances(handlerType);

        foreach (dynamic handler in handlers)
        {
            handler.Handle((dynamic)domainEvent);
        }
    }
}

Container 之前在包含此方法的 class 中提供,但它是 SimpleInjector IContainer.

的一个实例

NewOrderEvent 的示例 IDomainEventHandler 如下所示:

 public class NewOrderEventHandler : IDomainEventHandler<NewOrderEvent>
 {
    public void Handle(NewOrderEvent args)
    {
        // Event handled here.
    }
 }

样本 IDomainEvent 看起来像:

public class NewOrderEvent : IDomainEvent
{
    public IOrder Order { get; set; }
}

IDomainEventHandler<> 在 SimpleInjector 中注册为:

var assemblies = new[] {
            // Other assemblies use this too
            typeof(NewOrderEventHandler).Assembly, // Event Handlers
        };

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

当我 运行 方法时,出现以下异常:

No registration for type IEnumerable<IDomainEventHandler<NewOrderEvent>> could be found. There is, however, a registration for IDomainEventHandler<NewOrderEvent>; Did you mean to call GetInstance<IDomainEventHandler<NewOrderEvent>>() or depend on IDomainEventHandler<NewOrderEvent>?

我不太明白为什么这不起作用 - 谁能帮忙?

错误让我相信您使用的是 Register 而不是 RegisterCollection:使用 Register 注册的项目使用 GetInstance 解决,使用 [=11] 注册的项目=] 被解析为 GetAllInstances.