For the latest MediatR version 12.x February 2023:
As of version 12, Mediatr offers support for registering Handlers with the Microsoft Dependency Injection framework directly within the Mediatr namespace, and so can be achieved when calling AddMediatR
on the Service collection.
services.AddMediatR(cfg =>
cfg.RegisterServicesFromAssembly(typeof(Ping).Assembly));
Where Ping
is a type that is contained in an assembly that should be scanned to register Handlers, etc.
Note: The additional NuGet package (described below) that had been created to support such Registration in previous versions of MediatR is no longer required; details of this, and other breaking changes can be found at the Migration Guide on GitHub:
For earlier Mediatr versions up to and including 11.x:
In July 2016, Jimmy Bogard, author of MediatR, had released a package to register MediatR, and Handlers, with the ASP.Net Core DI service (which is actually the interface IServiceCollection
, implemented in Microsoft.Extensions.DependencyInjection
and which is not restricted to use solely within ASP.Net Core).
MediatR.Extensions.Microsoft.DependencyInjection
Link to GitHub Project.
Link to NuGet Package information.
A blog post introducing the package and it's capabilities can be found here
Example registration copied directly from the (very short) blog post:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddMediatR(typeof(Startup));
}
This package performs several functions to enable MediatR, including the required scanning of assemblies for Handlers:
You can either pass in the assemblies where your handlers are, or you can pass in Type objects from assemblies where those handlers reside. The extension will add the IMediator interface to your services, all handlers, and the correct delegate factories to load up handlers.
Note: This package is no longer required as of Mediatr version 12.
For all versions
Once the dependency registration has been specified using the relevant method described above, within your controllers, you can just use an IMediator dependency:
public class HomeController : Controller
{
private readonly IMediator _mediator;
public HomeController(IMediator mediator)
{
_mediator = mediator;
}
public IActionResult Index()
{
var pong = _mediator.Send(new Ping {Value = "Ping"});
return View(pong);
}
}
services.AddTransient(typeof (IMediator), BuildMediator().GetType());
– Whomsoeverservices.AddScoped<SingleInstanceFactory>(p => t => p.GetRequiredService(t));
andservices.AddScoped<MultiInstanceFactory>(p => t => p.GetRequiredServices(t));
are factory methods that are injected into mediator and resolve the notifications (multi) or requests (single) – ThimbleIMediator
itself you can register asservices.AddScoped<IMediator,Mediator>()
as it has public constructor and the delegates are registered in previous step. In the example the last one is did automatically via Scrutor scanning – Thimble