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
  • 相关阅读:
    Nginx目录结构与配置文件详解
    最新Sql语句来啦
    一个小工具帮你搞定实时监控Nginx服务器
    javascript学习笔记基于对象续
    Buffer解析
    使用用户自定义控件实现asp.net的的权限管理
    asp.net java 的十大关键技术
    程序员的基本素质
    无法编译的异常解决
    程序员的健康作息时间 该看看啊
  • 原文地址:https://www.cnblogs.com/chucklu/p/13092079.html
Copyright © 2011-2022 走看看