NotificationHandler gets called twice

See original GitHub issue

Hello,

unfortunately, I´ve discovered that the NotificationHandler is getting called twice. I´ve read a few articles on the web but the problem is still not fixed.

I am using the following versions:

  1. MediatR 10.0.1
  2. MediatR.Extensions.FluentValidation.AspNetCore 2.0.0
  3. MediatR.Extensions.Microsoft.DependencyInjection 10.0.1

This is how I register MediatR

            services.AddMediatR(typeof(IInstaller).Assembly);
            services.AddValidatorsFromAssembly(typeof(IInstaller).Assembly);
            ValidatorOptions.Global.LanguageManager.Culture = new CultureInfo("de-DE");

The type ‘IInstaller’ is in the corresponding project where my NoticationHandlers and RequestHandlers are.

This is how I publish a Notification

    public abstract class DomainEvent {
        public Guid EventId { get; set; }
        public bool IsPublished { get; set; }
        public DateTimeOffset DateOccurred { get; set; }
        protected DomainEvent() {
            EventId = Guid.NewGuid();
            DateOccurred = DateTimeOffset.Now;
        }
    }
public class UserStateChangedEvent : DomainEvent {
        public ApplicationUser ApplicationUser { get; }
        public UserStateChangedEvent(ApplicationUser applicationUser) {
            ApplicationUser = applicationUser;
        }
    }
private async Task DispatchDomainEventsAsync(ICollection objectsToSave, ICollection objectsToDelete) {
            IEnumerable<DomainEvent> saveDomainEvents = objectsToSave.OfType<AggregatedRoot>().Where(x=> x.DomainEvents != null).Where(x => x.DomainEvents.Any()).SelectMany(x=>x.DomainEvents);
            IEnumerable<DomainEvent> deleteDomainEvents = objectsToDelete.OfType<AggregatedRoot>().Where(x=> x.DomainEvents != null).Where(x => x.DomainEvents.Any()).SelectMany(x=>x.DomainEvents);
            IEnumerable<DomainEvent> concatDomainEvents = saveDomainEvents.Concat(deleteDomainEvents);
            foreach (DomainEvent domainEvent in concatDomainEvents) {
                domainEvent.IsPublished = true;
                await _domainEventService.Publish(domainEvent);
            }
        }
public class DomainEventService : IDomainEventService {

        private readonly IPublisher _publisher;
        public DomainEventService(IPublisher publisher) {
            _publisher = publisher;
        }

        public async Task Publish(DomainEvent domainEvent) {
            await _publisher.Publish(GetNotificationCorrespondingToDomainEvent(domainEvent));
        }
        
        private INotification GetNotificationCorrespondingToDomainEvent(DomainEvent domainEvent)
        {
            return (INotification)Activator.CreateInstance(
                typeof(DomainEventNotification<>).MakeGenericType(domainEvent.GetType()), domainEvent)!;
        }
    }
    public class UserStateChangedEventHandler : INotificationHandler<DomainEventNotification<UserStateChangedEvent>> {     
        public async Task Handle(DomainEventNotification<UserStateChangedEvent> notification, CancellationToken cancellationToken) {
            //DoStuff
        }
    }

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:8

github_iconTop GitHub Comments

1reaction
disekscommented, Aug 30, 2022

I think that it is not a Mediatr problem. I have investigated my project and Mediatr source code and found out that the handler was registered twice. In my case I’m using Autofac and MediatR.Extensions.Autofac.DependencyInjection:

public void ConfigureContainer(ContainerBuilder builder)
{
    builder.RegisterMediatR(typeof(Startup).Assembly);
    builder.RegisterAssemblyTypes(Assembly.GetEntryAssembly()).AsImplementedInterfaces();
 }

According to my investigation, both RegisterMediatR and RegisterAssemblyTypes registered my handler. I’ve checked Autofac registration list and saw that handler was registered twice:

var types = container.ComponentRegistry.Registrations
     .Where(r => typeof(MyNotificationHandler).IsAssignableFrom(r.Activator.LimitType))
     .Select(r => r.Activator.LimitType);

So, I think you need to look towards dependencies registration

Read more comments on GitHub >

github_iconTop Results From Across the Web

MediatR: INotification handler is being called multiple times
Handle method is being called multiple times - I noticed it seems to be relative to number of command handlers registered in Startup.cs,...
Read more >
Diagnosing and Fixing MediatR Container Issues
As IntegrationEventHandler is registered twice. That means we leave ourselves open for that handler to get called twice. Not ideal!
Read more >
Flutter app runs twice when using background messenging ...
I was trying to setup notifications for an app when I ran into this. ... other handlers run twice for each notification, my...
Read more >
the page load event execute twice - Microsoft Q&A
The Page_load fires once unless the page is called twice or in very rare cases the Page_Load event is manually called. the code...
Read more >
JS code runs twice, on client and server? (not sure) : r/nextjs
Hello, I'm relatively new to web dev and I've been working on a personal project lately until I've got this problem.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found