jbogard / MediatR

Simple, unambitious mediator implementation in .NET
Apache License 2.0
10.91k stars 1.16k forks source link

Add single RequestHandler to DI #979

Closed sanderjochems-whyellow closed 5 months ago

sanderjochems-whyellow commented 8 months ago

How can I add a single RequestHandler to Microsoft.Extensions.DependencyInjection?

When using the services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(Startup).Assembly)) it registers all RequestHandlers.

jbogard commented 8 months ago

Why?

sanderjochems-whyellow commented 8 months ago

I have a project which contains multiple vertical slice in a single project. The vertical slices are then used by multiple projects.

Each vertical slice has it's own startup which add services to the dependency injection service collection.

public static class FeatureStartupExtensions
{
    public static IServiceCollection AddCreateTransactionFeature(this IServiceCollection services, IConfiguration configuration, IHostEnvironment environment)
    {
        return services
            .AddMediatR() // TODO: add one RequestHandler (CreateTransactionHandler)
            .AddTransient<IMovementOrderHeaderFactory, MovementOrderHeaderFactory>()
            .AddTransient<IMovementOrderLinesFactory, MovementOrderLinesFactory>()
            .AddTransient<INotificationService, NotificationService>()
            .AddTransient<IUnloadingPointService, UnloadingPointService>();
    }
}

These startup extensions are then added to the required projects.

By separating the slices in this way every feature is completely isolated from the others.

jbogard commented 8 months ago

But they all run in-process so there's really not isolation? Anyway no, there's not a way to add a single handler. Just register the handler manually if you want that kind of explicitness. I don't think it matters though, all handlers go into the same service collection bucket. Just register MediatR once to scan for all the handlers and your slices can then register their own individual dependencies.

github-actions[bot] commented 6 months ago

This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 14 days.

github-actions[bot] commented 5 months ago

This issue was closed because it has been stalled for 14 days with no activity.