In a recent post, I talked about a project where the requirement is to create modules that can be used in an ASP.NET webapplication and in Sharepoint 2007, where I wanted to have separations of concerns. The way I solved this is: creating ASP.NET UserControl libraries (inside their own ASP.NET Webapplication project) that we package inside Sharepoint webparts. During development we test and debug the modules in a separate ASP.NET webapplication. We use pre-build events to copy the ascx files from the UserControl libraries to this webapplication and because we set a reference to the  webapplications, the dll’s are available already. Scott Guthrie has a tutorial on his website that explains how we do this. 

In the post I said I wanted to leverage Unity as our Inversion of Control Container and I was thinking about using the WCSF, because I wanted to use the MVP design pattern.
After some prototyping, I came to the conclusion using WCSF was not practical for our purpose.  Still I wanted to use the MVP pattern, because of unit-testing and loose coupling needs. I could not use MVC, because of the Sharepoint requirements.

The Model-View-Presenter pattern is different from MVC or Model-View-Controller in the sense that with MVC the Controller is where the request comes in and the Controller is where you control (what’s in a name…) your View and what you get from the Model.
With MVP the request comes in at the View, the View than delegates it to the Presenter that will get data from the Model and returns it back to the View.

Model View Presenter pattern Pic 1.: Model View Presenter pattern

The solution I finally found to be working really good is using the MVP design pattern and Unity in the following manner.

Model View Presenter UserControl diagramPic 2.:Model View Presenter Class Diagram 

As you can see in picture 2 the Model, View and Presenter all are implementing an interface. Practicing Interface based programming sets the door wide open for leveraging an Inversion of Control container, or IoC container. In my case I am using Unity, because I am doing this project for a client who is heavily into using Microsoft tools. All Presenters are derived from the abstract class Presenter<TView>.


Pic 3.: Interfaces used in MVP diagram

Why the interfaces?
Using Interfaces for all these parts of our component makes it easy to use an IoC container. Our objects are loosely coupled and we can switch out the concrete implementations easily, because we program against the interfaces. Say we want to test the Presenter and to avoid having a dependency on a data store or some service we want to switch the Model out for an implementation that returns the same hard coded objects each time. all we have to do is create this ‘mock’ Model that implements the IZaakModel interface (on Picture 3) and we are good to go.
To make this even more appealing: if we use an IoC container we only have to change the configuration in the container to start to use this other Model…

Here a listing of the Presenter of picture 2.

   1:  using System;
   2:  using Microsoft.Practices.Unity;
   3:  using HC.Interfaces.Zaak;
   4:  using HC.Mvp;
   5:  using HC.Domain;
   6:   
   7:  namespace HC.Presenters.Zaak
   8:  {
   9:      public class ZaakDetailPresenter: Presenter<IZaakDetailsView>, IZaakDetailsPresenter
  10:      {
  11:          private Zaak CurrentZaak{ get; set;}
  12:   
  13:          [Dependency]
  14:          public IZaakService Service { get; set;}
  15:   
  16:          private IZaakModel _model;
  17:          public ZaakDetailPresenter([Dependency] IZaakModel model)
  18:          {
  19:              _model = model;
  20:              _model.CurrentZaakChanged += new EventHandler<DataEventArgs<Zaak>>(_model_CurrentZaakChanged);
  21:          }
  22:   
  23:          void _model_CurrentZaakChanged(object sender, DataEventArgs<Zaak> e)
  24:          {
  25:              CurrentZaak = e.Data;
  26:              View.ShowCurrentZaakOnView(CurrentZaak);
  27:          }
  28:   
  29:          public override void OnViewInitialized()
  30:          {
  31:              base.OnViewInitialized();
  32:          }
  33:   
  34:          public override void OnViewLoaded()
  35:          {
  36:              View.ShowCurrentZaakOnView(CurrentZaak);
  37:          }
  38:   
  39:      }
  40:  }

Listing 1: Presenter

 

Because the Presenter (in listing 1) is derived from the Presenter<TView> abstract class, it is necessary to tell the Presenter of what type its View will be. Because we  use the Interface again, all we have to do is let Unity (our IoC container) do the work to supply the concrete implementation for this Interface. On line 13 of listing 1 we see the Dependency attribute, in this case the attribute will be used by Unity to resolve the concrete implementation of the IZaakService interface for the property (Service) on which the attribute is decorated that is configured.

The Model
The Model from picture 1 implements the Interface IZaakModel, and is responsible for getting the data if the Presenter asks for it and for letting the Presenter know that it has got this data and handing it over to the Presenter.

   1:  using System;
   2:  using Microsoft.Practices.Unity;
   3:  using HC.Domain;
   4:  using HC.Mvp;
   5:  using HC.Interfaces.Zaak;
   6:   
   7:  namespace HC.Models
   8:  {
   9:      public class ZaakModel : IZaakModel
  10:      {
  11:          public event EventHandler<DataEventArgs<Zaak>> CurrentZaakChanged;
  12:   
  13:          private IZaakService _datasource;
  14:          private Zaak _CurrentZaak;
  15:   
  16:          public ZaakModel([Dependency] IZaakService datasource)
  17:          {
  18:              _datasource = datasource;
  19:          }
  20:   
  21:          #region IZaakModel Members
  22:          public void LoadCurrentZaakById(int zaakId)
  23:          {
  24:              CurrentZaak = _datasource.GetZaakById(zaakId);
  25:          }
  26:   
  27:          public Zaak CurrentZaak
  28:          {
  29:              get { return _CurrentZaak; }
  30:              set
  31:              {
  32:                  _CurrentZaak = value;
  33:                  OnCurrentZaakChanged(new DataEventArgs<Zaak>(_CurrentZaak));
  34:              }
  35:          }
  36:   
  37:          public virtual void OnCurrentZaakChanged(DataEventArgs<ZaakExtended> e)
  38:          {
  39:              if (CurrentZaakChanged != null)
  40:                  CurrentZaakChanged(this, e);
  41:          }
  42:          #endregion
  43:      }   
  44:  }

Listing 2.: The Model

In listing 2 the Model is listed, is also depending on Unity for the resolving of the concrete implementations for interfaces. It implements IZaakModel  and thus implements the LoadCurrentZaakById method and the CurrentZaak property. When the  LoadCurrentZaakById (line 22, listing 2) is called it fills the CurrentZaak property calling a method on an object that implements the IZaakService interface (the private _datasource variable that is set by the ZaakModel constructor using Unity).

When the CurrentZaak property is filled the setter (line 30, listing 2) is used and in the setter the CurrentZaakChanged event is raised. Every object that subscribes to this event will recieve the change.

In listing 1 we can see on line 20 the Presenter has attached the event and will recieve this change. On line 26 of listing 1 the ShowCurrentZaakOnView method of the View is called.

The View
In ASP.NET a request will load an aspx page, the view is where the request starts, the view than delegates responsibility to the Presenter.

   1:  using System;
   2:  using Microsoft.Practices.Unity;
   3:  using HC.Interfaces.Zaak;
   4:  using HC.Mvp;
   5:  using HC.Domain;
   6:   
   7:  namespace HC.ZaakModule
   8:  {
   9:      public partial class ZaakDetails : System.Web.UI.UserControl,IZaakDetailsView
  10:      {
  11:          IZaakDetailsPresenter _presenter;
  12:          public event EventHandler UserControlLoaded;
  13:          [Dependency]
  14:          public IZaakDetailsPresenter Presenter
  15:          {
  16:              get
  17:              {
  18:                  return _presenter;
  19:              }
  20:              set
  21:              {
  22:                  if (value == null)
  23:                      throw new ArgumentNullException("value is null");
  24:              
  25:                  _presenter = value;
  26:                  _presenter.View = this;
  27:              }
  28:          }
  29:      
  30:          protected void Page_Load(object sender, EventArgs e)
  31:          {
  32:              if (!this.IsPostBack)
  33:              {
  34:                  this._presenter.OnViewInitialized();
  35:              }
  36:              this._presenter.OnViewLoaded();
  37:          }
  38:          
  39:          #region Control Init (Unity)
  40:          protected override void OnInit(EventArgs e)
  41:          {
  42:              IUnityContainer container = Container.Instance;
  43:              _presenter = container.Resolve<IZaakDetailsPresenter>();
  44:              _presenter.View = this;
  45:              base.OnInit(e);
  46:          }
  47:          #endregion
  48:      
  49:          #region IZaakDetailsView Members
  50:          public void ShowCurrentZaakOnView(Zaak zaak)
  51:          {
  52:              DetailsAlgemeenControl.CurrentZaak = zaak;
  53:              DetailsVoortgangControl.CurrentZaak = zaak;
  54:          }
  55:          #endregion
  56:      }
  57:  }

Listing 3.: The View

On line 50 of listing 3 the OnInit method of the UserControl (our view) is listed. Inside the body of this method we can see that we instantiate a variable named container (type IUnityContainer) and put a Container.Instance in it. On the next line (line 53) we fill the private member _presenter (the private member that is used in our property Presenter) by letting the container resolve the interface  IZaakDetailsPresenter. On the next line (line 54) we tell the Presenter that it’s View is this control. We have to do this here, because the View is where the request comes in. So this is the first component of our App that is loaded. Because my requirement is to create modules that can be used in Sharepoint or in ASP.NET, I cannot use the Global.asax to resolve the concrete implementations.

The ascx, or html is very straightforward, so i am not showing it, because I feel it is in the way of what i want to tell. I hope it is clear enough without it.

The Container
So how can
the container variable that is of Type IUnityContainer, an interface, on line 52 know what concrete class to Resolve? and where does Container come from. What does Container.Instance do?
In a class called container I create a UnityContainer using the Singleton design pattern:

   1:  using System;
   2:  using Microsoft.Practices.Unity;
   3:  using HC.Models;
   4:  using HC.Interfaces.Zaak;
   5:  using HC.Services;
   6:  using HC.Presenters.Zaak;
   7:   
   8:  namespace HC.ZaakModule
   9:  {
  10:      public class Container
  11:      {
  12:   
  13:          private static IUnityContainer instance;
  14:   
  15:          private Container() { }
  16:   
  17:          public static IUnityContainer Instance
  18:          {
  19:              get
  20:              {
  21:                  if (instance == null)
  22:                  {
  23:                      instance = new UnityContainer();
  24:   
  25:                      instance.RegisterType<IZaakModel, ZaakModel>(new ContainerControlledLifetimeManager())
  26:                          .RegisterType<IZaakService, ZaakService>()
  27:                          .RegisterType<IZaakView, Zaken>()
  28:                          .RegisterType<IZaakPresenter, ZaakPresenter>()
  29:                          .RegisterType<IZaakListView, ZaakList>()
  30:                          .RegisterType<IZaakSearchPresenter, ZaakSearchPresenter>()
  31:                          .RegisterType<IZaakSearchView, ZaakSearch>()
  32:                          .RegisterType<IZaakListPresenter, ZaakListPresenter>()
  33:                          .RegisterType<IZaakDetailsView, ZaakDetails>()
  34:                          .RegisterType<IZaakDetailsPresenter, ZaakDetailPresenter>();
  35:                  }
  36:                  return instance;
  37:              }
  38:          }
  39:      }
  40:  }

Listing 4.: The Container

 

Singleton
Using the singleton design pattern
the registering of the concrete implementation to the interfaces will be done only once, as you can see in the module I am building there are more components that follow the same pattern, so using a singleton was in my opinion the way to go in this case.
I choose to use a simple version of the singleton, I make a class called container, this class has a private static variable called instance (of type IUnityContainer).
The class has a private constructor, so the class cannot be directly created. Furthermore the class has a public static property (type IUnityContainer) that can only get a single instance of a IUnityContainer, because in the getter we check if the private member called instance (type IUnityContainer) is null or has been filled already, if it is filled the instance it contains is returned, but if it is null a new UnityContainer is instantiated and using a Fluent Interface all Interfaces and their concrete implementations are registered inside it before we pass it to the instance variable, after that the instance it contains is returned.

On line 25 of listing 4 the RegisterType has a parameter and the following RegisterType methods of the fluent interface have not. With new ContainerControlledLifeManager() as a parameter into the RegisterType method we tell Unity to resolve the concrete implementation as a singleton. In the case of the Model I need it to be a singleton, because the model is the only place some state need to be held in my architecture.

Configuration file
Configuring the registration in a  configuration file is also possible, in my case I did not wanted to do it, but I can understand that in some cases that is exactly what you want.

Conclusion
Ofcourse a lot more has to be considered when using this architecture, but I hope this article helps in understanding how you can use Dependency injection or Inversion of control and the Model view Presenter pattern to create maintainable and robust applications.

Henry Cordes
My thoughts exactly…