A Layered ASP.NET MVC Application [with StructureMap] – Part V

Posted: May 5, 2009 in ASP.NET
Tags: ,

In my last post I had completed the demo of building a layered ASP.NET MVC application(the bookmark list application).This week I thought of adding the StructureMap container to that demo.I am quite new to StructureMap but I loved it’s usage of Fluent Interfaces and DSL a lot.I have primarily applied what I understood from it’s online documentation.I wanted to keep the option of plugging in another container later in this application.So I defined my own container interface as shown below:

    public interface  IContainer {
       
void AddInstanceConfig<I, T>(string key) where T:I; //Configures an instance with instance key,type and concrete type
       
void StartContainer(); //Starts the Container
       
object GetInstance<I>(string instanceName); //Returns an object instance based on the instance key/name
       
void DestroyContainer(); //destroys the container and releases the references


As a next step I have developed an Adapter for StructureMap container implementing this interface as shown below:

 
 class StructureMapAdapter:IContainer {       
       private StructureMap.Container container  = null;
       
private Registry r = null;
        private static StructureMapAdapter instance = new StructureMapAdapter();       private StructureMapAdapter() { }
       
/// <summary>
       
/// Get the StructureMapContainer instance
       
/// </summary>
       
/// <returns></returns>
        public static StructureMapAdapter GetAdapterInstance() {

           
return instance;
       
}
/// <summary>
       
/// Configures the object in the container
       
/// </summary>
       
/// <typeparam name=”I”>Type to be configured</typeparam>
       
/// <typeparam name=”T”>Concrete type to be configured</typeparam>
       
/// <param name=”key”>Instance key name</param>
        public void AddInstanceConfig<I, T>(string key) where T:I{
            if (r == null) r = new Registry();
           
r.ForRequestedType<I>().AddInstances( y =>
           
{
                       
y.OfConcreteType<T>().WithName(key);
           
});
       
}
       
/// <summary>
       
/// Creates the container instance.
       
/// </summary>
        public void StartContainer() {

           
if (container == null) {
               
if (r!= null) {
                   
container = new StructureMap.Container(r);
               
}
           
}
       
}
 
   
} 
    
        public object GetInstance<I>(string instanceName) {
           
return container.GetInstance<I>(instanceName);
       
}
       
/// <summary>
       
/// Destroys the Container
       
/// </summary>
        public void DestroyContainer() {

           
//TODO:Need to call dispose on all instances
            throw new NotImplementedException();

       
}

 Note the following lines of code used to configure an instance.

            if (r == null) r = new Registry();
           
r.ForRequestedType<I>().AddInstances( y =>
           
{
                       
y.OfConcreteType<T>().WithName(key);
           
});

This creates a StructureMap Registry class and configures the registry in such a way that when the container is requested to return a concrete type for type I with name=key it will return T.See how easily(fluently) we can express what we want to do in terms of programming language.This makes StructureMap great.Similarly, the following lines of code returns an instance of I with instance name/key = instancename

return container.GetInstance<I>(instanceName);

As I want the code to be flexible to adapt to different containers I have kept a factory class in between to return the instance of the right container instance.At present it returns an instance of StructureMapAdapter only.

    public class ContainerFactory {
       
public static IContainer GetContainer() {
           
return StructureMapAdapter.GetAdapterInstance();
       
}
   
}
 
Now we have to develop the custom controller factory for ASP.NET MVC.This class will implement the System.Web.Mvc.IControllerFactory interface and it’s following methods:
 
  • IController CreateController(RequestContext requestContext, string controllerName)
    • Creates the controller instance based on controllerName.We have to call IContainer.GetInstance here.
  • void ReleaseController(IController controller)
    • Destroys the controller instance

I have passed a preconfigured instance of IContainer to the ControllerFactory constructor.

  public class ControllerFactory :IControllerFactory {
       
private IContainer container;
       
public ControllerFactory(IContainer container) {
           
this.container = container;
            
       
}       
       public IController CreateController(
          System.Web.Routing.RequestContext requestContext, string controllerName) {
           
return container.GetInstance<IController>(controllerName) as IController;
       
}   
        public void ReleaseController(IController controller) {
           
if (controller is IDisposable) {
               
(controller as IDisposable).Dispose();
           
}
       
}

How to plug in our container and controller factory to hook into the ASP.NET MVC application?First we have to create the container instance,configure and start the container within Application_Start in Global.asax.cs as shown below:

 IContainer c = ContainerFactory.GetContainer();
c.AddInstanceConfig<IController, 
           BookMarkListWebApp.Controllers.BookmarkController>(“Bookmark”);
 
c.AddInstanceConfig<IController, 
           BookMarkListWebApp.Controllers.AccountController>(“Account”);
c.StartContainer();
 
Then we have to create the controller factory and set it using the System.Web.Mvc.ControllerBuilder as shown below:
ControllerBuilder.Current.SetControllerFactory(new ControllerFactory(c));
 
So now ControllerFactory is up and running with StructureMap container.In my next post I will try to replace the same by Unity.  

   

Advertisements
Comments
  1. sankarsan says:

    There was some issues related to code formatting and post got distorted.Now it’s corrected.
    Regret the inconvenience caused.

  2. […] to VoteA Layered ASP.NET MVC Application [with StructureMap] – Part V (5/5/2009)Tuesday, May 05, 2009 from sankarsanIn my last post I had completed the demo of building a layered […]

  3. A Layered ASP.NET MVC Application [with StructureMap] – Part V – Sankarsan…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

  4. vishalg says:

    could u plz prove sample code with mvc 1.0 ,
    i wld be very useful.!!!!!!
    thanx in advance

  5. Great post. Itd be cool if you could update it to use MVC3 and WCF Web Api.

  6. Frank says:

    Hello Sankarsa,
    Greetings from Brazil!
    First of all, although this serie is kinda old, I’d like to congratulate for this amazing content you have wrote about. I have read these specific 5 articles about MVC and WCF using Service Interface Pattern and I’m still in doubt about the advantages of it. I understand that using this approach we can decouple the business logic from the UI, also we can achieve the separation of concerns, maybe easing the manutenability as well as facilitating to scale out the application, however do you see any other advantage? Do you think it’s really worth it? Do yourself have any other article talking about that or even an external link? I’d like to use this approach in my next projects. Thank you so much! I look forward to hearing your answer! 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s