【问题标题】:Autofac Open Generic Decorator with multiple interface causes circular dependency resolving具有多个接口的 Autofac Open Generic Decorator 导致循环依赖解析
【发布时间】:2019-10-02 19:57:38
【问题描述】:

我有以下接口:

public interface ICommandHandler<T>
{
    void Handle(T command);
}

public class TransactionalCommandHandlerDecorator<T> : ICommandHandler<T>
{
    private readonly ICommandHandler<T> _handler;
    public TransactionalCommandHandlerDecorator(ICommandHandler<T> handler)
    {
        _handler = handler;
    }
    public void Handle(T command)
    {
    }
}

我有一个实现两个命令处理程序的具体类:

public class Handler : ICommandHandler<CreateLocation>
                        ,ICommandHandler<ModifyLocation>
{
    public void Handle(CreateLocation command)
    {

    }

    public void Handle(ModifyLocation command)
    {
    }
}

我的注册如下:

 builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
            .AsClosedTypesOf(typeof(ICommandHandler<>))
            .InstancePerLifetimeScope();

    builder.RegisterGenericDecorator(typeof(TransactionalCommandHandlerDecorator<>), typeof(ICommandHandler<>));

解析“处理程序”类会导致 autofac 在无限循环中循环解析装饰器和处理程序,这会导致 StackOverflowException。如果我将“处理程序”更改为仅实现一个接口,那么它将毫无问题地工作。

知道如何解决这个问题吗?

【问题讨论】:

  • 对我来说似乎是一个错误。我想建议在 Autofac 问题页面上报告这个,但显然,你 already done that :)
  • 您是否尝试从程序集扫描中排除装饰器,以便它不会尝试自行装饰?
  • 是的。我使用以下代码从程序集扫描中排除了“TransactionalCommandHandlerDecorator”:.Where(a=> !typeof(TransactionalCommandHandlerDecorator).IsAssignableFrom(a)) 但这没有帮助。

标签: c# dependency-injection decorator autofac


【解决方案1】:

这是一个bug,将在 Autofac 的未来版本中解决。该修复看起来需要对 API 的另一部分进行重大更改,因此需要作为 v5.0 的一部分发布。

与此同时,解决此问题的一种方法是创建单独的注册。

var builder = new ContainerBuilder();
builder.RegisterType<Handler>().As<ICommandHandler<CreateLocation>>();
builder.RegisterType<Handler>().As<ICommandHandler<ModifyLocation>>();
builder.RegisterGenericDecorator(typeof(TransactionalCommandHandlerDecorator<>), typeof(ICommandHandler<>));
var container = builder.Build();

var instance = container.Resolve<ICommandHandler<CreateLocation>>();

【讨论】:

    猜你喜欢
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 2020-06-15
    相关资源
    最近更新 更多