2016-04-13 23 views
0

を使用してStrategyパターンを作成するときにこれは私の依存性の注入のセットアップです:循環依存関係エラー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)); 
    } 
} 

リポジトリとコンテキストが別のプロジェクトです。

私は(DIツリーの解決)GetStrategyメソッドを呼び出すと、私はこのエラーを取得:

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に基づいて関連する戦略を解決することができます。 私は何が間違っていますか?

質問があまりにもコンパクトであるかどうかがわかります。ですから、これはStackoverflowExceptionで終わるだろう解決し、参照

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)

答えて

0

循環依存関係のようなものを意味します。リゾルバはあなたがサイクルを特定し、それを破る必要があるため...

FoobarためStrategy1ためRepository1ためFoobarためStrategy1を解決サイクルで回します。実際には本当にそれを破るか、そうでない場合は、InSingletonScope()またはInRequestScope()(該当する場合)のようなスコープを使用して、それをctorに注入するのではなく遅延注入することで逃げるかもしれません。あなたはNinject.Extensions.FactoryとLazy<T>またはFunc<T>を使用することができます。

+0

ありがとうございました。あなたの答えは私の問題を解決しませんでしたが、正しい方向に私を導いてくれました。この問題は実際にスコープに関するものでした。どうやら私のコンテキストはInRequestScope()にあって、私のリポジトリはどんなスコープにもありませんでした。これらをInRequestScope()に変更すると動作します。戦略はまだ範囲内にある必要はありませんが、リポジトリとコンテキストが別々のプロジェクトにあることが関係していると思います。 – danskov

関連する問題