Home | Blog | Screencasts | Projects
# Thursday, March 12, 2009

My last post described a really simple scenario where I used a HttpHandler to configure StructureMap, then I showed some code that is used to replace the ‘new’ operation used to create a new instance like: ObjectFactory.GetInstance<NumberPrinter>()

 

This might seem a little clunky because you need to remember to use the StructureMap ObjectFactory, not all programmers are created equal, so it might slip through the cracks. What would a framework look like if it embraced the concept of DI?

Well it turns out that the ASP.MVC framework was designed from the ground up (or a mile up as the case may be, it was started on a plane flight). To configure StructureMap with ASP.NET MVC, firstly it’s OK to modify the global.asax (since this isn’t a SharePoint solution):

 

        protected void Application_Start()
        {
           
            StructureMapConfiguration.AddRegistry(new DIRegistry());

            ControllerBuilder.Current.SetControllerFactory( typeof(StructureMapControllerFactory)   );

        }

Here we configure StructureMap with the same method as my last post by using the StructureMapConfiguration.AddRegistry method. The second line is more interesting, we tell the MVC framework that we want StructureMapControllerFactory to be the factory class that creates our controllers. So the code to this class looks like:

 

public class StructureMapControllerFactory : DefaultControllerFactory
   
{
        protected override IController GetControllerInstance(Type controllerType)
        {
            try
           
{
                return ObjectFactory.GetInstance(controllerType) as System.Web.Mvc.Controller;

            }
            catch (StructureMapException x)
            {
                System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave());
                throw;
            }
        }       
    }

 

That’s pretty cool, so what it means now is that we can create our controllers to take an instance of anything we want to inject. Continuing from the example with a simple Number interface:

 

public class TestController : Controller
{
        INumber _number;
        public TestController(INumber number)
        {
            _number = number;
        }

        public ActionResult Index()
        {
           
            return View(_number.GetNumber());
        }

}

 

This means that the controller has been passed an instance of INumber that has been created by StructureMap. Once you do the initial setup, it’s now pretty hard to make any mistakes in regards to not calling the proper Create methods.

Thursday, March 12, 2009 11:30:00 AM (E. Australia Standard Time, UTC+10:00)  #    Comments [0] - Trackback
ASP.NET MVC | code | StructureMap
Statistics
Total Posts: 191
This Year: 0
This Month: 0
This Week: 0
Comments: 41