Varuna
Varuna

Reputation: 125

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?

Upvotes: 4

Views: 9430

Answers (2)

Aidos
Aidos

Reputation: 2765

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

Upvotes: 9

pfx
pfx

Reputation: 23214

I assume you are using Mediatr v3.0.x.

You are missing the registrations for the SingleInstanceFactory and MultiInstanceFactory as here below.

builder.Register<SingleInstanceFactory>(ctx => {
    IComponentContext c = ctx.Resolve<IComponentContext>(); 
        return type => {
            Object o; 
            return c.TryResolve(type, out o) ? o : null; 
        };
    }); 

builder.Register<MultiInstanceFactory>(ctx => {
    IComponentContext c = ctx.Resolve<IComponentContext>(); 
    return type => (IEnumerable<Object>)c.Resolve(typeof(IEnumerable<>).MakeGenericType(type)); 
    });

Upvotes: 2

Related Questions