【问题标题】:DryIoc recursive dependency exception with Factory (Func<>)DryIoc 递归依赖异常与 Factory (Func<>)
【发布时间】:2020-09-02 09:13:47
【问题描述】:

嘿,我已经从 Autofac 切换到 DryIoc。我的代码以前可以工作,但现在导致异常“解析时检测到递归依赖项”。 (代码已简化)

public class AFactory {
   public AFactory(Func<A> getA){ }
}

public class BFactory {
   public BFactory(Func<B> getB, AFactory factory){ }
}

public class A { 
   public A(IrrelevantService service, BFactory factory){ }
}

实际的代码很复杂,所以假设这个代码结构是有必要的。

它正在尝试解决 AFactory --> A --> BFactory --> AFactory 这就是问题所在。但是由于它使用的是 Func 所以应该没问题吗? (或者至少在 Autofac 中)。

有没有办法注册它使其不会抛出这个异常?

【问题讨论】:

标签: c# ioc-container dryioc


【解决方案1】:

这里是reason from the Func wrapper docs

默认情况下,不允许递归依赖。

下面的文档或later section 中描述了该修复程序。

Here are all possible fixes:

using System;
using DryIoc;
                    
public class Program
{
    public static void Main()
    {
        var c = new Container(
            //rules => rules.WithFuncAndLazyWithoutRegistration() // fix1: make everything lazy resolvable preventing the recursive dependency check!
        );
        
        c.Register<A>(
            //setup: Setup.With(asResolutionCall: true) // fix2: makes A a dynamically resolvable
        );
        c.Register<AFactory>();
        
        c.Register<B>();
        c.Register<BFactory>(
            setup: Setup.With(asResolutionCall: true) // fix3: makes BFactory a dynamically resolvable - the fix is here and not in B because the BFactory is already loops to AFactory and making B dynamic is not enough
        );
        
        c.Register<IrrelevantService>();
        
        var af = c.Resolve<AFactory>();
        Console.WriteLine(af);
    }
    
    public class AFactory {
       public AFactory(Func<A> getA){ }
    }

    public class BFactory {
       public BFactory(Func<B> getB, AFactory aFactory){ }
    }

    public class A { 
       public A(IrrelevantService service, BFactory bFactory){ }
    }
    
    public class B {}
    public class IrrelevantService {}
}

【讨论】:

  • 感谢您的帮助。我最终使用了 Lazy (在 BFactory 的初始化程序中)。我尝试使用 fix2(和 fix 3)并成功创建了对象,但是当我调用 getA() 时,它抛出了相同的异常。 (可能是我的代码的问题)。
  • 嗯,基本上这是一个不错的 DryIoc 不可知的解决方法,添加到文档中:)
猜你喜欢
  • 2023-03-12
  • 2021-03-31
  • 1970-01-01
  • 2015-03-07
  • 1970-01-01
  • 1970-01-01
  • 2019-08-23
  • 2018-01-03
  • 2015-03-06
相关资源
最近更新 更多