using System.Threading.Tasks;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
public interface IEvent{}
public interface IEventNotification<TEvent> : INotification
TEvent Event { get; init; }
public class EventNotification<TEvent> : IEventNotification<TEvent>
public EventNotification(TEvent myEvent)
public TEvent Event { get; init; }
public interface IEventNotificationHandler<TEvent> : INotificationHandler<IEventNotification<TEvent>>
public class TestEvent : IEvent
public class FirstEventNotificationHandler : IEventNotificationHandler<TestEvent>
public Task Handle(IEventNotification<TestEvent> notification, CancellationToken cancellationToken)
Console.WriteLine("First notification handler");
return Task.CompletedTask;
public class SecondEventNotificationHandler : IEventNotificationHandler<TestEvent>
public Task Handle(IEventNotification<TestEvent> notification, CancellationToken cancellationToken)
Console.WriteLine("Second notification handler");
return Task.CompletedTask;
public class CustomNotificationHandlerDecorator<TDomainEvent> : IEventNotificationHandler<TDomainEvent>
where TDomainEvent : IEvent
private readonly INotificationHandler<IEventNotification<TDomainEvent>> _decorated;
public CustomNotificationHandlerDecorator(IEventNotificationHandler<TDomainEvent> decorated)
public Task Handle(IEventNotification<TDomainEvent> notification, CancellationToken cancellationToken)
Console.WriteLine("I am the custom decorator!");
_decorated.Handle(notification, cancellationToken);
Console.WriteLine("Decorator job completed\n");
return Task.CompletedTask;
protected readonly IPublisher _mediatr;
public Application(IPublisher mediatr)
Console.WriteLine("Publishing the test event...\n");
_mediatr.Publish(new EventNotification<TestEvent>(new TestEvent()));
Console.WriteLine("All done.");
private static IContainer CompositionRoot()
var builder = new ContainerBuilder();
builder.RegisterType<Application>();
builder.RegisterAssemblyTypes(typeof(IMediator).GetTypeInfo().Assembly).AsImplementedInterfaces();
builder.RegisterSource(new Autofac.Features.Variance.ContravariantRegistrationSource());
var mediatrOpenTypes = new[]
typeof(INotificationHandler<>)
foreach (var mediatrOpenType in mediatrOpenTypes)
.RegisterAssemblyTypes(typeof(Program).GetTypeInfo().Assembly)
.AsClosedTypesOf(mediatrOpenType)
.AsImplementedInterfaces();
var services = new ServiceCollection();
builder.Populate(services);
builder.RegisterGenericDecorator(typeof(CustomNotificationHandlerDecorator<>),typeof(INotificationHandler<>));
public static void Main()
CompositionRoot().Resolve<Application>().Run();