Tutorial :Adding additional dependency using Castle Windsor


I am tying to register a component into the IWindsorContainer i.e.

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

When i resolve the view i want to also want to create the Presenter so that i can subscribe to any events that are generated by the view. Can this be accomplished during the registration process or do i need some kind of Facility?

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();    }  }  

I have written a custom registration but its not working as expected

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);                  }  }  


Usually I do this differently:

  1. View gets the Presenter injected in the constructor. This way you ensure both are created at the same time (when you resolve IView from the container)
  2. The presenter does not receive the view in the constructor. Rather, I add the code to assign it in the View's constructor explicitly:
public View(Presenter presenter)  {     this.presenter = presenter;     presenter.AssignView (this);  }  

Of course, it could be the other way around - but then you would have to resolve the Presenter, not the IView.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »