2

In MVC, the view sends events to the controller and the controller sends these events to the model. The model sends changes to the view through the controller.

This introduces a cyclic dependency which makes dependency injection(I'm manually injecting dependencies through the constructor - not using a framework) not possible(resulting in harder to unit test code). I read a potential solution but can't figure out how to apply this.

Can someone point me to a solution?

Thanks in advance.

4

2 回答 2

2

Another solution is to let your IoC container create factories for you and Inject those instead, look at this similar problem with an example MVP implementation. The Concrete view needs a Presenter but the Presenter needs an IView (the abstraction). It's more like a circular reference than a dependency.

public interface IView
{
    string Name { get; set; }
}

public interface IPresenterFactory<TController>
{
   TController Create<TView>(TView view);
}

public class ConcreteView : IView
{
    private Presenter _Presenter;
    public ConcreteView(IPresenterFactory<Presenter> presenter)
    {
        this._Presenter = presenter.Create(this);
    }
 }

 public class Presenter
 {
      public Presenter(IView view)
      {
         this._View = view;
      }
 }

The presenter factory can easily make use of and wrap your IoC container and then just generate your factories as needed. Unit testing it is also easy, because you can very easy just create a Mock of IPresenterFactory and construct the Presenter or Controller that you need.

于 2012-07-20T09:53:07.543 回答
1

One solution you have found yourself but you may have not noticed yet:

In MVC, the view sends events to the controller and the controller sends these events to the model. The model sends changes to the view through the controller.

The View and the Model could publish events (think Observer Pattern) to notify the Controller, meaning that you don't have a dependency on the Controller neither in the Model nor in the View.

于 2012-07-20T09:37:46.443 回答