-
Notifications
You must be signed in to change notification settings - Fork 0
Dependency Injection
Mediatron plugs directly into Microsoft.Extensions.DependencyInjection, so setup only takes one line.
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();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);Once registered, IMediator is available anywhere through constructor injection:
public class ProductsController : ControllerBase
{
private readonly IMediator _mediator;
public ProductsController(IMediator mediator)
{
_mediator = mediator;
}
}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