一部のクラスには、次のようなコンストラクターがあります。
public class MyComponent : BaseComponent, IMyComponent
{
public MyComponent(IPostRepository postsRepo, int postId, ICollection<string> fileNames)
{
// ...
}
}
IPostRepository
揮発性の依存関係ですが、アプリケーションの開始時に初期化できます。postId および fileNames 引数は、実行時にのみ認識されます。
Castle Windsor (重要な場合は 3.2.0) を使用しIPostRepository
て、ランタイム コンストラクターのパラメーターを許可しながら依存関係の注入を処理するにはどうすればよいですか?
(1 つのアプローチは をリファクタリングすることかもしれませんがMyComponent
、コードの他の多くの部分が既に を参照しているため、これは重要な作業になりますMyComponent
。)
これが私がこれまでに得たところです:私はMyComponentFactory
. のインターフェースは次のMyComponentFactory
ようになります
public interface IMyComponentFactory
{
IMyComponent Create(params object[] args);
}
これIMyComponentFactory
は、次のように上のレイヤー (私の場合はコントローラー) に挿入されます。
public class MyController : Controller
{
private IMyComponentFactory _myComponentFactory;
public MyController(IMyComponentFactory myComponentFactory)
{
_myComponentFactory = myComponentFactory;
}
public ActionResult MyAction(int postId)
{
List<string> fileNames = new List<string>();
// ...
// Creates a new instance of the resolved IMyComponent with the IPostRepository that was injected into IMyComponentFactory and the run time parameters.
IMyComponent myComponent = _myComponentFactory.Create(postId, fileNames);
// Now do stuff with myComponent
return View();
}
}
IMyComponentFactory
最後に、次のようにコンポジション ルートにmy を登録して、Castle Windsor にファクトリ実装を作成させようとしました。
// Add Factory facility
container.AddFacility<TypedFactoryFacility>();
container.Register(Component.For<IMyComponentFactory>().AsFactory());
これを行うDependencyResolverException
と、次のメッセージが表示されます
'Playground.Examples.Components.MyComponent' (Playground.Examples.Components.MyComponent) のオプションではない依存関係を解決できませんでした。パラメータ「postId」タイプ「System.Int32」
エラーは理にかなっており、のカスタム実装を作成する必要があると推測していますがIMyComponentFactory
、どうすればよいかわかりません。