I'm playing around with the new ASP.NET Core and are currently creating a API that I want to call from a JavaScript frontend.
I want to use the mediator pattern to reduce the coupling, and I have found the Library MediatR from Jimmy Bogard.
My problem consist in wiring it up using the build in DI, I have tried looking at the examples, but can't see to crack how it binds into the ConfigureServices method in the startup class.
Do anybody have any insight?
UPDATE: I got it working, from my ConfigureService method:
services.AddScoped<SingleInstanceFactory>(p => t => p.GetRequiredService(t));
services.Scan(scan => scan
.FromAssembliesOf(typeof(IMediator), typeof(MyHandler.Handler))
.AddClasses()
.AsImplementedInterfaces());
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:
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 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.
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);
}
}