Search code examples
c#.netsimple-injector

SimpleInjector.GetAllInstances throwing unexpected error


I have the following method which raises a domain event. An instance of an IDomainEvent is passed to the method and it is handled using instances of IDomainEventHandler supplied by SimpleInjector's GetAllInstances method.

The method looks like this:

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 is supplied previously in the class that contains this method, but it is an instance of a SimpleInjector IContainer.

An example IDomainEventHandler for a NewOrderEvent looks like:

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

And a sample IDomainEvent looks like:

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

The IDomainEventHandler<> is registered with SimpleInjector as such:

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

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

When I run the method, I get the following exception:

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>?

I don't quite understand why this isn't working - can anyone help?


Solution

  • The error leads me to believe you are using Register instead of RegisterCollection: items registered with Register are resolved with GetInstance, items registered with RegisterCollection are resolved with GetAllInstances.