【问题标题】:Autofac Generic Multiple InterfaceAutofac 通用多接口
【发布时间】:2015-07-07 18:05:07
【问题描述】:

我正在尝试解决一个类似下面的通用接口,但在尝试运行应用程序时遇到异常。

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”。

我不确定如何修复此错误。

【问题讨论】:

  • 您不应该在没有 IEnumerable 的情况下解析 _componentContext.Resolve&lt;IHandler&lt;TEvent&gt;&gt;(); 吗?

标签: c# dependency-injection domain-driven-design inversion-of-control autofac


【解决方案1】:

您尝试将ApplicationUserCreatedEventHandler 注册为IHandler&lt;&gt; 的开放类型,但此类型不是IHandler&lt;&gt;,而是IHandler&lt;ApplicationUserCreatedEvent&gt;,因此您必须将其注册为它。

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

您将能够通过这种方式解决它:

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

顺便说一句,如果你想注册一个开放类型,你可以使用这样的东西:

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

ApplicationUserCreatedEventHandler&lt;T&gt; 像这样:

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>>>();

【讨论】:

  • 我正在尝试解析多个事件处理程序。就我而言,它没有解决我的 implementations 。我想我做错了什么。我正在遵循您的第一种方法。 var handlers = _componentContext.Resolve>>();在我的引导类 builder.RegisterType().As(typeof(IHandler));我正在通过 IDomainEvent 接口而不是具体实现,因为我正在尝试解决所有实现 IDomainEvent
  • ApplicationUserCreatedEventHandler 不能转换为 IHandler&lt;IDomainEvent&gt;。要允许这种转换,您必须将您的类型转换为协变类型,这是不可能的,因为您有一个接受 T 作为参数的方法。
  • 顺便说一句,为什么您需要所有事件,而不仅仅是特定 T 的事件?此类问题的另一个常见解决方案是为IHandler 提供非通用基本接口。
  • 我需要捕获所有实现 IHandler 的事件处理程序,例如这个公共类 ApplicationUserCreatedEventHandler : IHandler。我也会尝试非通用方法。
  • 非通用解决方案对我有用,就像这个公共接口 IHandler { void Handle(IDomainEvent args); } 。但是,如果我可以使用 Autofac 解决通用解决方案,那就太好了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-30
  • 1970-01-01
  • 1970-01-01
  • 2012-02-15
  • 2023-03-15
相关资源
最近更新 更多