[英]Autofac Generic Multiple Interface
我正在尝试解决一个通用接口,如下所示,但是在尝试运行该应用程序时出现异常。
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
}
}
我正在像下面这样在global.asax中注册
var builder = new ContainerBuilder();
builder.RegisterType<ApplicationUserCreatedEventHandler>().As(typeof (IHandler<>));
return builder.Build();
}
这就是我使用IComponentContext解决依赖项的方式。
var handlers = _componentContext.Resolve<IEnumerable<IHandler<TEvent>>>();
因此,当我尝试运行此代码时,它给了我下面的错误。
无法将类型'Service.ActionService.DomainEventHandler.ApplicationUserCreatedEventHandler'分配给服务'Domain.Core.DomainEvent.IHandler`1'。
我不确定如何解决此错误。
您尝试将ApplicationUserCreatedEventHandler
注册为IHandler<>
的开放类型,但是此类型不是IHandler<>
,而是IHandler<ApplicationUserCreatedEvent>
因此必须将其注册为它。
builder.RegisterType<ApplicationUserCreatedEventHandler>()
.As(typeof(IHandler<ApplicationUserCreatedEvent>));
您将可以通过以下方式解决它:
container.Resolve<IEnumerable<IHandler<ApplicationUserCreatedEvent>>>();
顺便说一句,如果您想注册一个开放类型,可以使用如下代码:
builder.RegisterGeneric(typeof(ApplicationUserCreatedEventHandler<TUserCreatedEvent>))
.As(typeof(IHandler<>));
和ApplicationUserCreatedEventHandler<T>
像这样:
public class ApplicationUserCreatedEventHandler<TUserCreatedEvent>
: IHandler<TUserCreatedEvent>
where TUserCreatedEvent : ApplicationUserCreatedEvent
{
public void Handle(TUserCreatedEvent args)
{
if (args == null) throw new ArgumentNullException("args");
// Code
}
}
您仍然可以通过以下方式解决它:
container.Resolve<IEnumerable<IHandler<ApplicationUserCreatedEvent>>>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.