MediatR Extensions for Microsoft Dependency Injection Released

To help those building applications using the new Microsoft DI libraries (used in Orleans, ASP.NET Core, etc.), I pushed out a helper package to register all of your MediatR handlers into the container.

MediatR.Extensions.Microsoft.DependencyInjection

To use, just add the AddMediatR method to wherever you have your service configuration at startup:

public void ConfigureServices(IServiceCollection services)
{
  services.AddMvc();

  services.AddMediatR(typeof(Startup));
}

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

And you’re good to go. Enjoy!

About Jimmy Bogard

I'm a technical architect with Headspring in Austin, TX. I focus on DDD, distributed systems, and any other acronym-centric design/architecture/methodology. I created AutoMapper and am a co-author of the ASP.NET MVC in Action books.
This entry was posted in ASPNetCore, MediatR. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Paul Wheeler

    Awesome!

  • How does this work where you have a postgres and a mssql handler for example that implement the one IRequestHandler. At the moment I check at app start what db we’re using and then register the relevant handler. Is there any funky way of handling that in aspnet core?

    • jbogard

      Not as far as I can tell. Registration in .NET Core is still painful – you can use the Scrutor library to help (but it doesn’t handle generic variance atm, I had to borrow from StructureMap).

      If it were any complexity beyond what this library does, I’d just switch to a real container. That’s what we’re shooting for on our teams – use the built-in until it doesn’t work, then switch to a real one.

      • I’ve realised this won’t work for me anyway as I’m using Nancy :) :)

        • jbogard

          LOL no it doesn’t. But it’s a great blueprint, I’d recommend this approach for any container. I just don’t want to create extensions for every single f’ing container out there.

  • Andrej Milas

    this looks way too easy. its a trap..

  • Dejan Miličić

    Do you have an advice how to simulate decorator pattern in this new DI, in order to achieve what is described here https://lostechies.com/jimmybogard/2014/09/09/tackling-cross-cutting-concerns-with-a-mediator-pipeline/

  • alex

    Works like a charm. Thank you