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
  • 相关阅读:
    第 5 章 Nova
    第 5 章 Nova
    第 5 章 Nova
    第 5 章 Nova
    第 5 章 Nova
    第 5 章 Nova
    第 5 章 Nova
    vba:提取字符串中间字符
    vba:根据给定单元格搜索目标值
    vba:合并当前目录下所有工作簿的全部工作表
  • 原文地址:https://www.cnblogs.com/chucklu/p/13092079.html
Copyright © 2011-2022 走看看