Search code examples
autofacmediatr

Cannot resolve parameter 'MediatR.ServiceFactory serviceFactory' (MediatR with Autofac)


I'm attempting to run MediatR with Autofac in .NET Framework 4.6.2.

My registration:

public class MediatorModule : Autofac.Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterSource(new ContravariantRegistrationSource());
        builder.RegisterAssemblyTypes(typeof(IMediator ).Assembly).AsImplementedInterfaces();
        builder.RegisterType<HealthCheckQueryHandler>().As<IRequestHandler<HealthCheckQuery, HttpStatusCode>>();
    }
}

My controller:

[RoutePrefix("api/v1/healthcheck")]
public class HealthCheckController : ApiController
{
    private readonly IMediator _mediator;

    public HealthCheckController(IMediator mediator)
    {
        _mediator = mediator;
    }

    [HttpGet]
    [Route("")]
    public async Task<HttpStatusCode> Get()
    {
        var query = new HealthCheckQuery();
        var result = await _mediator.Send(query);
        return result;
    }
}

When I try to hit this api method, I receive the following error: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MediatR.Mediator' can be invoked with the available services and parameters:\r\nCannot resolve parameter 'MediatR.ServiceFactory serviceFactory' of constructor 'Void .ctor(MediatR.ServiceFactory)

The wiki (https://github.com/jbogard/MediatR/wiki) asks us to register SingleInstanceFactory and MultiInstanceFactory. But Visual Studio is not able to resolve either of these symbols.

How can I resolve this to get MediatR working with Autofac?


Solution

  • I know this is an old post, but in case anyone else googles for this.

    You're missing registering the ServiceFactory instance.

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

    Taken from here: MediatR Examples