C# Autofac+MediatR and IRequestExceptionHandler not working with Net Framework

Viewed 237

I'm building a test project (C# and Net Framework 4.7.2) to test CQRS using MediatR(9.0.0) and Autofac(6.3.0) as DI resolver. Command handlers (registered as IRequestHandler<,>) are working fine. The thing is that I want to catch any exception thrown within any Command handler. I did a lot of research but couldn't find any working solution. Here is what I have:

  • Autofac registration (builder is ContainerBuilder):
builder.RegisterType<Mediator>()
    .As<IMediator>()
    .InstancePerLifetimeScope();

// Open handlers.
var mediatrOpenTypes = new[] {
    typeof(IRequestHandler<,>),
    typeof(IRequestExceptionHandler<,,>)
};

foreach (var mediatrOpenType in mediatrOpenTypes)
{
    builder
        .RegisterAssemblyTypes(assemblies)
        .AsClosedTypesOf(mediatrOpenType)
        .AsImplementedInterfaces();
}

builder.Register<ServiceFactory>(ctx =>
{
    var c = ctx.Resolve<IComponentContext>();
    return t => c.Resolve(t);
});

builder.RegisterType<MediatorCommandBus>().As<ICommandBus>().InstancePerLifetimeScope();
  • The Exception handler:
public class ExceptionHandler<TRequest, TResponse, TException>
    : IRequestExceptionHandler<TRequest, TResponse, TException> where TException : Exception
{
    // Variables.
    private readonly IDomainNotificationHandler _notifications;


    public ExceptionHandler(IDomainNotificationHandler notifications)
    {
        _notifications = notifications;
    }
    
    public async Task Handle(TRequest request, TException exception, RequestExceptionHandlerState<TResponse> state,
        CancellationToken cancellationToken)
    {
        var exceptionType = exception.GetType();

        if (!TextHelper.IsNullOrEmptyOrWhitespace(exception.Message))
            _notifications.Add(exceptionType.Name, exception.Message);

        state.SetHandled(default);
    }
}

I don't know what I'm doing wrong, but CommandHandler is never invoked.

0 Answers
Related