Unity resolving generic event handlers

1.2k Views Asked by At

I'm using Unity to register all my domain event handlers like such :

public static void RegisterTypes(IUnityContainer container)
{
    container.RegisterType<IDomainEventHandler<ProductCreated>, ProductCreatedHandler>(new PerRequestLifetimeManager());
}

My handler looks like this :

public class ProductCreatedHandler : IDomainEventHandler<ProductCreated>
{
    public void Handle(ProductCreated domainEvent)
    {
        // Handle the event
    }
}

My domain event looks like this :

public class ProductCreated : IDomainEvent
{
    private Product product;

    public ProductCreated(Product product)
    {
        this.product = product;
    }
}

And I raise this event using :

var product = new Product()
{
    ProductGuid = Guid.NewGuid().ToString(),
    ProductCode = productCode,
    ProductName = productName,
};

DomainEvents.Raise<ProductCreated>(new ProductCreated(product));

And I handle raised events with the following code :

public static void Raise<T>(T args) where T : IDomainEvent
{
    if (Container != null)
    {
        foreach (var handler in Container.ResolveAll<IDomainEventHandler<T>>())
        {
            handler.Handle(args);
        }
    }
}

Using the inspector, T is a ProductCreated type but Container.ResolveAll<IDomainEventHandler<T>>() does not resolve anything, even though through the inspector I can see that the Container does have a registration to this registered type IDomainEventHandler with the mapped type being ProductCreatedHandler

Why is the container not resolving the generic type that I register at the start ?

1

There are 1 best solutions below

0
On BEST ANSWER

ResolveAll only resolves named registrations, try registering your handler with a name, like so:

container.RegisterType<IDomainEventHandler<ProductCreated>, ProductCreatedHandler>("ProductCreatedHandler", new PerRequestLifetimeManager());

This can be seen under Remarks in the documentation for ResolveAll<T>():

Be aware that this method does NOT return an instance for the default (unnamed) registration.