1. 程式人生 > >Mediator 基於內存的發布訂閱

Mediator 基於內存的發布訂閱

pen context 基於內存 log rom pre num mark pub

Github Mediator

使用方法

    /// <summary>
    /// 返回值 BaseEntity
    /// </summary>
    public class Ping1 : IRequest<BaseEntity>
    {
        public string Name { get; set; }
        public int Val { get; set; }
    }

    /// <summary>
    /// 不帶返回值
    /// </summary>
    public class Ping2 : IRequest
    {
        public string Name { get; set; }
        public int Val { get; set; }
    }

    public class BaseEntity
    {
        public bool Flag { get; set; }
        public int Val { get; set; }
    }
    public class PingHandler1 : IRequestHandler<Ping1, BaseEntity>
    {
        public Task<BaseEntity> Handle(Ping1 request, CancellationToken cancellationToken)
        {
            Console.WriteLine("傳入值 {0} .帶有返回值", request.Val);
            return Task.FromResult(new BaseEntity() { Val = request.Val * 2 });
        }
    }
    public class PingHandler2 : IRequestHandler<Ping2>
    {
        public Task Handle(Ping2 message, CancellationToken cancellationToken)
        {
            Console.WriteLine("傳入值 {0} .不帶返回值", message.Val);
            return Task.FromResult("");
        }
    }
        static void Main(string[] args)
        {

            DoAsync();
            Console.ReadLine();
        }
        public static async void DoAsync()
        {
            var mediator = BuildMediator();

            var response = await mediator.Send(new Ping1 { Val = 666 });

            Console.WriteLine("傳出值 {0} .", response.Val);

            await mediator.Send(new Ping2 { Val = 666 });

            Console.ReadLine();
        }

        private static IMediator BuildMediator()
        {
            var builder = new ContainerBuilder();
            builder.RegisterAssemblyTypes(typeof(IMediator).GetTypeInfo().Assembly).AsImplementedInterfaces();//註冊IMediator自身的組件

            var mediatrOpenTypes = new[]
            {
                typeof(IRequestHandler<,>),
                typeof(IRequestHandler<>),
                typeof(INotificationHandler<>),
            };

            foreach (var mediatrOpenType in mediatrOpenTypes)
            {
                //
                //builder
                //    .RegisterAssemblyTypes(typeof(Ping).GetTypeInfo().Assembly)
                //    .AsClosedTypesOf(mediatrOpenType)
                //    .AsImplementedInterfaces();
                builder
                .RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .AsClosedTypesOf(mediatrOpenType)
                .AsImplementedInterfaces();
            }

            // It appears Autofac returns the last registered types first 顯示指定泛型解析
            //builder.RegisterGeneric(typeof(RequestPostProcessorBehavior<,>)).As(typeof(IPipelineBehavior<,>));
            //builder.RegisterGeneric(typeof(RequestPreProcessorBehavior<,>)).As(typeof(IPipelineBehavior<,>));
            //builder.RegisterGeneric(typeof(GenericRequestPreProcessor<>)).As(typeof(IRequestPreProcessor<>));
            //builder.RegisterGeneric(typeof(GenericRequestPostProcessor<,>)).As(typeof(IRequestPostProcessor<,>));
            //builder.RegisterGeneric(typeof(GenericPipelineBehavior<,>)).As(typeof(IPipelineBehavior<,>));
            //builder.RegisterGeneric(typeof(ConstrainedRequestPostProcessor<,>)).As(typeof(IRequestPostProcessor<,>));
            //builder.RegisterGeneric(typeof(ConstrainedPingedHandler<>)).As(typeof(INotificationHandler<>));

            builder.Register<SingleInstanceFactory>(ctx =>
            {
                var c = ctx.Resolve<IComponentContext>();
                return t => c.Resolve(t);
            });

            builder.Register<MultiInstanceFactory>(ctx =>
            {
                var c = ctx.Resolve<IComponentContext>();
                return t => (IEnumerable<object>)c.Resolve(typeof(IEnumerable<>).MakeGenericType(t));
            });

            var container = builder.Build();

            // The below returns:
            //  - RequestPreProcessorBehavior
            //  - RequestPostProcessorBehavior
            //  - GenericPipelineBehavior

            //var behaviors = container
            //    .Resolve<IEnumerable<IPipelineBehavior<Ping, Pong>>>()
            //    .ToList();

            var mediator = container.Resolve<IMediator>();

            return mediator;
        }

輸出:

技術分享圖片

Mediator 基於內存的發布訂閱