Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac register interface MediatR

i'm having trouble registering the IRequest and IRequestHandler interface with Autofac. This code works:

var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(typeof(IMediator).GetTypeInfo().Assembly).AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof(Ping).GetTypeInfo().Assembly).AsImplementedInterfaces();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

Now i want to make this more flexible to avoid having to register all the classes that uses the interfaces.

I tried this without luck:

builder.RegisterGeneric(typeof(IRequest<>)).AsImplementedInterfaces();
builder.RegisterGeneric(typeof(IRequestHandler<,>)).AsImplementedInterfaces();

This is my Ping class:

public class Ping : IRequest<Pong>
{
    public string Message { get; set; }
}

public class Pong
{
    public string Message { get; set; }
}

public class PingHandler : IRequestHandler<Ping, Pong>
{
    public Pong Handle(Ping message)
    {
        return new Pong { Message = message.Message + " Pong" };
    }
}

Any ideas?

like image 939
user943369 Avatar asked Mar 02 '16 11:03

user943369


1 Answers

RegisterGeneric method is meant to register open generic types, and this is not your case here.

If you use .RegisterAssemblyTypes().AsImplementedInterfaces(), it should handle types implementing IRequest<T> and IRequestHandler<T1, T2> as well. But if you want to separate your registration of request and request handler types, you could do it with the following code:

builder
    .RegisterAssemblyTypes(typeof(IRequest<>).Assembly)
    .Where(t => t.IsClosedTypeOf(typeof(IRequest<>)))
    .AsImplementedInterfaces();

builder
    .RegisterAssemblyTypes(typeof(IRequestHandler<>).Assembly)
    .Where(t => t.IsClosedTypeOf(typeof(IRequestHandler<>)))
    .AsImplementedInterfaces();

As a parameter of .RegisterAssemblyTypes() method you should pass assembly where you have your request types and request handler types defined, respectively. In the sample code I assumed you have defined interface and implementing types in the same assembly.

like image 91
tdragon Avatar answered Nov 09 '22 14:11

tdragon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!