使用Castle Windsor添加额外的依赖项

时间:2009-07-22 00:07:55

标签: c# castle-windsor

我想把一个组件注册到IWindsorContainer,即

_container.Register(Component.For<IView>().ImplementedBy<View>());
_container.Register(Component.For<Presenter>());

当我解析视图时,我还想创建Presenter,以便我可以订阅视图生成的任何事件。这可以在注册过程中完成,还是需要某种设施?

public interface IView
{
  event Action<string> Process;
}

public class View : IView
{
  public event Action<string> Process;
}

public class Presenter
{
  public Presenter(IView view)
  {
    view.Process += (args) => this.DoSomeStuff();
  }
}

我已经编写了自定义注册,但它没有按预期工作

public class ViewRegistration<TView> : IRegistration where TView : IView
{
    private Type _implementation, _presenter;

    public ViewRegistration<TView> ImplementedBy<TImplementation>() where TImplementation : TView
    {
        _implementation = typeof(TImplementation);
        return this;
    }

    public ViewRegistration<TView> Using<TPresenter>()
    {
        _presenter = typeof(TPresenter);
        return this;
    }

    public void Register(IKernel kernel)
    {
        var model = kernel.ComponentModelBuilder.BuildModel(_implementation.FullName, typeof(TView), _implementation, null);
        if (_presenter != null)
        {
            var test = kernel.ComponentModelBuilder.BuildModel(_presenter.FullName, _presenter, _presenter, null);

            model.AddDependent(test);
        }
        kernel.AddCustomComponent(model);            
    }
}

1 个答案:

答案 0 :(得分:0)

通常我会这样做:

  1. View获取构造函数中注入的Presenter。这样就可以确保两者同时创建(当您从容器中解析IView时)
  2. 演示者不会在构造函数中接收视图。相反,我添加代码以明确地在View的构造函数中分配它:
  3. public View(Presenter presenter)
    {
       this.presenter = presenter;
       presenter.AssignView (this);
    }
    

    当然,它可能是另一种方式 - 但是你必须解决Presenter,而不是IView。