2

一部のクラスには、次のようなコンストラクターがあります。

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、どうすればよいかわかりません。

4

2 に答える 2

1

次のようなことができないのはなぜですか。

public class MyComponentFactory : IMyComponentFactory
{
    private IPostRepository postRepository;

    public MyComponentFactory(IPostRepository postRepository)
    {
       this.postRepository = postRepository;
    }

    public IMyComponent Create(int postId, ICollection<string> fileNames)
    {            
        return new MyComponent(this.postRepository, postId, fileNames);
    }
}

メソッドで明示的なパラメーターを使用しますCreate

次にMyComponentFactory、インターフェイスに対してIMyComponentFactory(シングルトンとして)登録します

于 2013-04-05T20:19:38.533 に答える