Search code examples
c#asp.net-coreninjectmediatr

Is it possible to write one handler for multiple notifications in MediatR


I have such hierarchy

class Notification : INotification
{
    public string Message { get; set; }
}

class Notification1 : Notification
{
    public int Count { get; set; }
}

class Notification2 : Notification
{
    public string Detailes { get; set; }
}

is it possible for such notifications to be handled by one handler which will handle all child requests

public class CommandHandler : INotificationHandler<Notifcation>
{
    //universal handler
    public Task Handle(Notification notification)
    {
        //serialization and logging, don't care what body will command have
    }
}

Solution

  • Yes, you can make your handler generic with a generic constraint.

    public class CommandHandler<T> : INotificationHandler<T> where T : Notifcation
    {
        //universal handler
        public Task Handle(T notification)
        {
            //serialization and logging, don't care what body will command have
        }
    }