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