使用 ninject 创建策略模式时出现循环依赖错误

Cyclical dependency error when creating Strategy pattern using ninject

这是我的依赖注入设置:

dIcontainer.Bind<DBContext>().ToSelf().InRequestScope();

//Repository accepts a constructor parameter DBContext
dIcontainer.Bind<IRepository1, Repository1>();   
dIcontainer.Bind<IRepository2, Repository2>();

//All strategies accepts a constructor parameter of a repository interface
//There is one strategy per repository
dIcontainer.Bind(x => x.FromThisAssembly().SelectAllClasses().InheritedFrom<IStrategy>().BindSingleInterface());

//The factory accepts a constructor parameter of IEnumerable<IStrategy>
dIcontainer.Bind<StrategyFactory>().ToSelf();

工厂的实现:

public class StrategyFactory
{
    private IEnumerable<IStrategy> _strategies;

    public StrategyFactory(IEnumerable<IStrategy> strategies)
    {
        _strategies = strategies;
    }

    public IStrategy GetStrategy(string keyToMatch)
    {
        return _strategies.Single(strategy => strategy.IsStrategyMatch(keyToMatch));
    }
}

存储库和上下文在一个单独的项目中。

当我调用 GetStrategy 方法(解析 DI 树)时出现此错误:

Error activating IStrategy using binding from IStrategy to Strategy1 A cyclical dependency was detected between the constructors of two services.

如果我改为在每个策略构造函数中更新存储库:

public Strategy1()
{
     _repository = new Repository1(new DBContext());           
}

我在我的工厂里得到了一个完美的策略列表,可以根据keyToMatch解析出相关的策略。 我做错了什么?

让我知道问题是否过于紧凑。

循环依赖意味着:

Strategy1 needs Repository1 needs Foobar needs Strategy1 needs (and on and on and on, sorry but there's not enough disk space in the world to finish this example properly)

所以你看,解决这个问题会以 WhosebugException 结束。解析器将循环解析 Strategy1 for Foobar for Repository1 for Strategy1 for Foobar for ...

你需要找出循环并打破它。要么你真的破坏了它,要么你可能会让一个组件使用像 InSingletonScope()InRequestScope() 这样的范围(如适用)并延迟注入它而不是将它注入 ctor。您可以为此使用 Ninject.Extensions.Factory 和 Lazy<T>Func<T>