简体   繁体   中英

Autofac Generic Multiple Interface

I am trying to resolve one generic interface something like below but I am getting exception when trying to run the application .

public interface IHandler<in T> where T : IDomainEvent
{
    void Handle(T args);
}

public class ApplicationUserCreatedEventHandler : IHandler<ApplicationUserCreatedEvent>
{
    public void Handle(ApplicationUserCreatedEvent args)
    {
        if (args == null) throw new ArgumentNullException("args");
        // Code 
    }
}

I am registering in global.asax like below

    var builder = new ContainerBuilder();
    builder.RegisterType<ApplicationUserCreatedEventHandler>().As(typeof (IHandler<>));
    return builder.Build();
}

This is how I am resolving the dependency using IComponentContext .

var handlers = _componentContext.Resolve<IEnumerable<IHandler<TEvent>>>();

So When I am trying to run this code it gives me below error .

The type 'Service.ActionService.DomainEventHandler.ApplicationUserCreatedEventHandler' is not assignable to service 'Domain.Core.DomainEvent.IHandler`1'.

I am not sure how to fix this error.

You try to register ApplicationUserCreatedEventHandler as an open type of IHandler<> but this type is not a IHandler<> it is a IHandler<ApplicationUserCreatedEvent> so you have to register it as it.

builder.RegisterType<ApplicationUserCreatedEventHandler>()
       .As(typeof(IHandler<ApplicationUserCreatedEvent>));

And you will be able to resolve it this way :

container.Resolve<IEnumerable<IHandler<ApplicationUserCreatedEvent>>>();

By the way, if you want to register an open type you can use something like this :

builder.RegisterGeneric(typeof(ApplicationUserCreatedEventHandler<TUserCreatedEvent>))
       .As(typeof(IHandler<>));

and ApplicationUserCreatedEventHandler<T> like this :

public class ApplicationUserCreatedEventHandler<TUserCreatedEvent>
    : IHandler<TUserCreatedEvent>
    where TUserCreatedEvent : ApplicationUserCreatedEvent
{
    public void Handle(TUserCreatedEvent args)
    {
        if (args == null) throw new ArgumentNullException("args");
        // Code 
    }
}

And you will still be able to resolve it this way :

container.Resolve<IEnumerable<IHandler<ApplicationUserCreatedEvent>>>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM