是否可以在 MediatR 中为多个通知编写一个处理程序

问题描述 投票:0回答:1

我有这样的等级制度

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

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

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

此类通知是否可以由一个处理程序来处理,该处理程序将处理所有子请求

public class CommandHandler : INotificationHandler<Notifcation>
{
    //universal handler
    public Task Handle(Notification notification)
    {
        //serialization and logging, don't care what body will command have
    }
}
c# asp.net-core ninject mediatr
1个回答
0
投票

是的,可以。为基本类型

INotificationHandler<T>
实现
Notification
,它也会捕获任何派生的通知。

设置方法如下:

public class CommandHandler : INotificationHandler<Notification>
{
    // This universal handler will handle all derived notifications
    public Task Handle(Notification notification, CancellationToken cancellationToken)
    {
        // Perform your common handling, like serialization and logging
        Console.WriteLine($"Received notification: {notification.Message}");

        // You can use type-checking to handle each derived type differently if needed
        if (notification is Notification1 notification1)
        {
            Console.WriteLine($"Notification1 Count: {notification1.Count}");
        }
        else if (notification is Notification2 notification2)
        {
            Console.WriteLine($"Notification2 Details: {notification2.Detailes}");
        }

        return Task.CompletedTask;
    }
}

报名

确保您的处理程序已在

dependency injection
容器中注册:

services.AddMediatR(cfg => 
    cfg.RegisterServicesFromAssemblyContaining<CommandHandler>()
);
© www.soinside.com 2019 - 2024. All rights reserved.