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