[SOLVED] MediatR with ASP.NET Core DI

Issue

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());

Solution

As of July 2016, Jimmy Bogard, author of MediatR, has 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. Then in your controller, 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);
  }
}

Answered By – dmcquiggin

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *