[英]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.