jbogard / MediatR

Simple, unambitious mediator implementation in .NET
Apache License 2.0
11k stars 1.16k forks source link

how to handler INotificationHandler<DomainEventNotification<ApprovedEvent<T>>? #883

Closed neozhu closed 1 year ago

neozhu commented 1 year ago

please see my code structure

public class DomainEventNotification<TDomainEvent> : INotification where TDomainEvent : DomainEvent
{
    public DomainEventNotification(TDomainEvent domainEvent)
    {
        DomainEvent = domainEvent;
    }

    public TDomainEvent DomainEvent { get; }
}

public  class ApprovedEvent<T>: DomainEvent
{
    public ApprovedEvent(T entity)
    {
        Entity = entity;
    }

    public T Entity { get; }
}

public abstract class DomainEvent: INotification
{
    protected DomainEvent()
    {
        DateOccurred = DateTimeOffset.UtcNow;
    }
    public bool IsPublished { get; set; }
    public DateTimeOffset DateOccurred { get; protected set; }
}
public class ApprovedEventHandler<T> : INotificationHandler<DomainEventNotification<ApprovedEvent<T>>> where T : AuditableEntity
{
    public ApprovedEventHandler()
    {
        Console.WriteLine("ApprovedEventHandler");
    }
    public Task Handle(DomainEventNotification<ApprovedEvent<T>> notification, CancellationToken cancellationToken)
    {
        var domainEvent = notification.DomainEvent;
        throw new NotImplementedException();
    }
}

services.AddTransient(typeof(INotificationHandler<>), typeof(ApprovedEventHandler<>));
 services.AddMediatR(config => {
            config.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
            ....});

 await mediator.Publish(Activator.CreateInstance(typeof(DomainEventNotification<>).MakeGenericType(domainEvent.GetType()), domainEvent));

this ApprovedEventHandler not hit.why? how to solve it.

neozhu commented 1 year ago

I solve it. services.AddTransient(typeof(INotificationHandler<DomainEventNotification<ApprovedEvent>>), typeof(ApprovedEventHandler));

jbogard commented 1 year ago

The reason why this doesn't work is MediatR only looks for handlers of type INotificationHandler<TNotification>. It won't try to close more complex variations like this.