Skip to content

Dependency Injection

ferdi kurnaz edited this page Sep 1, 2026 · 2 revisions

Dependency Injection Setup

Mediatron plugs directly into Microsoft.Extensions.DependencyInjection, so setup only takes one line.

Registering Mediatron

Call AddMediatron and pass the assembly (or assemblies) that contain your handlers. Mediatron scans that assembly and registers every IRequestHandler, INotificationHandler, and IPipelineBehavior it finds — you do not need to register any of them by hand.

using Mediatron.Extensions;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMediatron(typeof(Program).Assembly);

var app = builder.Build();

Registering Handlers from Multiple Assemblies

If your handlers live in a different project (a common setup in layered applications), pass that assembly's type instead, or pass more than one assembly if your solution supports it:

builder.Services.AddMediatron(typeof(CreateProductCommandHandler).Assembly);

Using IMediator

Once registered, IMediator is available anywhere through constructor injection:

public class ProductsController : ControllerBase
{
    private readonly IMediator _mediator;

    public ProductsController(IMediator mediator)
    {
        _mediator = mediator;
    }
}

Behaviors Are Registered Automatically Too

Any class that implements IPipelineBehavior<TRequest> or IPipelineBehavior<TRequest, TResponse> in the scanned assembly is registered automatically. This works both for a behavior that applies to all requests (an open generic class, like LoggingBehavior<TRequest, TResponse>) and a behavior written for one specific request (like CreateProductCommandValidationBehavior). See Pipeline Behaviors for examples.

Next: Testing

Clone this wiki locally