jbogard / MediatR

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

polymorphic dispatch not as expected with INotificationHandler #904

Closed Rahul1994jh closed 1 year ago

Rahul1994jh commented 1 year ago

I am trying to use polymorphic dispatch with the INotificationHandler where I am facing certain issues:

here is the sample code for reprocibility

public class DefaultNotificationMessage : INotification {...}

public class DeaAuthIntegrationMessage : DefaultNotificationMessage {....}

// the default handler which needs to be executed if there is no specific handler available

public class DefaultNotificationSnsHandler : INotificationHandler where T : DefaultNotificationMessage { public virtual Task Handle(DefaultNotificationMessage notification, CancellationToken cancellationToken) { return Task.CompletedTask; } }

// execute specific handler only if available public class DeAuthIntegrationSnsHandler : DefaultNotificationSnsHandler { public override async Task Handle(DeaAuthIntegrationMessage notification, CancellationToken cancellationToken) { return Task.CompletedTask; } }

// this is how i have regitered the MediatR

services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblies( typeof(DefaultNotificationSnsHandler<>).Assembly, typeof(DeaAuthIntegrationSnsHandler<>).Assembly ));

// this is how message is getting pushed _mediator.Publish(new DeaAuthIntegrationMessage());

The problem is both DefaultNotificationSnsHandler and DeAuthIntegrationSnsHandler handle method gets executed although the handle in DeAuthIntegrationSnsHandler is merked virtual and is overriden in DeAuthIntegrationSnsHandler, I was expecting only DeAuthIntegrationSnsHandler handle method to be executed.

I am not using any third party DI container

jbogard commented 1 year ago

This is an issue with the stock container, not with MediatR.