zoukankan      html  css  js  c++  java
  • MediatR

    MediatR

    MediatR is a low-ambition library trying to solve a simple problem — decoupling the in-process sending of messages from handling messages. Cross-platform, supporting .NET Framework 4.6.1 and netstandard2.0.

    Setup

    Install the package via NuGet first: Install-Package MediatR

    MediatR has no dependencies. You will need to configure a single factory delegate, used to instantiate all handlers, pipeline behaviors, and pre/post-processors.

    You will need to configure two dependencies: first, the mediator itself. The other dependency is the factory delegate, ServiceFactory. The Mediator class is defined as:

    public class Mediator : IMediator
    {
        public Mediator(ServiceFactory serviceFactory)
    }

    The factory delegates are named delegates around a couple of generic factory methods:

    public delegate object ServiceFactory(Type serviceType);

    Declare whatever flavor of handler you need - sync, async or cancellable async. From the IMediator side, the interface is async-only, designed for modern hosts.

    Finally, you'll need to register your handlers in your container of choice.

    Autofac

    https://github.com/jbogard/MediatR/blob/master/samples/MediatR.Examples.Autofac/Program.cs

    The full example looks like:

    // Uncomment to enable polymorphic dispatching of requests, but note that
    // this will conflict with generic pipeline behaviors
    // builder.RegisterSource(new ContravariantRegistrationSource());
    
    // Mediator itself
    builder
        .RegisterType<Mediator>()
        .As<IMediator>()
        .InstancePerLifetimeScope();
    
    // request & notification handlers
    builder.Register<ServiceFactory>(context =>
    {
        var c = context.Resolve<IComponentContext>();
        return t => c.Resolve(t);
    });
    
    // finally register our custom code (individually, or via assembly scanning)
    // - requests & handlers as transient, i.e. InstancePerDependency()
    // - pre/post-processors as scoped/per-request, i.e. InstancePerLifetimeScope()
    // - behaviors as transient, i.e. InstancePerDependency()
    builder.RegisterAssemblyTypes(typeof(MyType).GetTypeInfo().Assembly).AsImplementedInterfaces(); // via assembly scan
    //builder.RegisterType<MyHandler>().AsImplementedInterfaces().InstancePerDependency(); 

    Basics

    MediatR has two kinds of messages it dispatches:

    • Request/response messages, dispatched to a single handler
    • Notification messages, dispatched to multiple handlers
  • 相关阅读:
    Redis操作命令大全
    Redis实用监控工具一览
    Redis缓存雪崩、缓存穿透、缓存击穿、缓存降级、缓存预热、缓存更新
    Redis GEO地理位置信息,查看附近的人
    详解redis持久化
    详解Supervisor进程守护监控
    详解Redis Cluster集群
    arduino使用rfid
    树莓派控制WS2812
    Arduino读取温湿度dh11+烟雾气体MQ2+彩灯ws2812
  • 原文地址:https://www.cnblogs.com/chucklu/p/13092079.html
Copyright © 2011-2022 走看看