• 仿照 MediatR实现了一个中介者模式Publish功能,使用同MediatR


    • 接口和实现
      public interface IMediator
        {
            Task Publish<T>(T notification, CancellationToken cancellationToken = default) where T : class, INotification;
        }
        public class Mediator : IMediator
        {
            private IServiceProvider _serviceProvider;
            private static ConcurrentDictionary<Type, Func<INotification, CancellationToken, Task>> _handle = new ConcurrentDictionary<Type, Func<INotification, CancellationToken, Task>>();
            public Mediator(
                IServiceProvider serviceProvider
                )
            {
                _serviceProvider = serviceProvider;
            }
            public Task Publish<T>(T notification, CancellationToken cancellationToken = default) where T : class, INotification
            {
                notification.IsNull("notification is null");
                var notificationType = notification.GetType();
                var func = _handle.GetOrAdd(notificationType, type =>
                {
                    Func<INotification, CancellationToken, Task> handle = null;
                    var handles = _serviceProvider.GetServices(typeof(INotificationHandler<T>));
                    foreach (var item in handles)
                    {
                        var generic = item.GetType().GetInterface($"{nameof(INotificationHandler<INotification>)}`1").GetGenericArguments().First();
    
                        if (!generic.Name.Equals(type.Name)) continue;
                        if (item is INotificationHandler<T> h )
                        {
                            handle += (x, y) => {
    
                               return  h.Handle((T)x,y);
                            };
                        }
                    }
                    return handle;
                });
                if (func == null) throw new Exception(message: $"对应的 INotificationHandler<{notificationType.Name}>的实现没有注入");
                return func((INotification)notification, cancellationToken);
            }
        }
    •  INotification 空接口
       public interface INotification
        {
        }
    • INotificationHandler<T>接口
        public interface INotificationHandler<T> where T : INotification 
        {
            Task Handle(T notification, CancellationToken cancellationToken=default(CancellationToken));
        }
    • 其他代码
        public static class CheckNull
        {
            public static void IsNull<T>(this T t,  string message="") 
            {
                if (t == null)
                {
                    throw new ArgumentNullException(nameof(t), message);
                }
            }
        }
    • 注入
        service.AddSingleton<IMediator, Mediator>();
        service.AddSingleton<INotificationHandler<MsgMonitorEvent>, MsgMonitorEventHandler>();
        service.AddSingleton<INotificationHandler<MsgMonitorEvent>, MsgMonitorNoticeHandler>();
    • Handler接口实现
         public class 
        MsgMonitorNoticeHandler:INotificationHandler<MsgMonitorEvent>
        {
            public async Task Handle(MsgMonitorEvent notification, CancellationToken cancellationToken = default)
            {
                Console.WriteLine("测试赛");
                await Task.CompletedTask;
            }
        }
    • 实现接口INotification的对象
        public class MsgMonitorEvent:INotification
        {
            public List<PerformancMonitorDto<MsgMonitorDto>> MonitorDtos { get; set; }
        }
    • 使用和MediatR完全一样,这样做的目的是不想代码中有太多依赖,可以在任意版本中切换重新编译可立即使用,2.1  3.1  5  6
  • 相关阅读:
    [翻译角]Headline English: A Captain Should Be Pitch Perfect at a Multitude of Skills (ESLPOD Blog)
    CF735D Taxes 哥德巴赫猜想判定素数 进一步猜想
    CF735C 数论平衡树叶子节点的最大深度贪心斐波那契条件归一化
    萌新的旅行&hdu5681单调队列的应用前缀和线段树ST表倍增解法
    CF731C Socks并查集(森林),连边,贪心,森林遍历方式,动态开点释放内存
    玲珑杯1007-A 八进制大数加法(实现逻辑陷阱与题目套路)
    关于石子合并
    codeforces724-B. Batch Sort
    codeforces724-A. Checking the Calendar 日期题
    如何筛选人
  • 原文地址:https://www.cnblogs.com/rengke2002/p/15044865.html
Copyright © 2020-2023  润新知