Click here to Skip to main content
15,879,535 members
Articles / Web Development

Dependency Injection with StructureMap in ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.64/5 (14 votes)
3 Jan 2011CPOL9 min read 159K   3.1K   61  
This article presents a simple example on dependency injection with StructureMap in ASP.NET MVC.
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using StructureMap;
using System.Collections.Specialized;

namespace StructureMapMVC
{
    // StructureMap ContollerFactory
    public class StructureMapControllerFactory : DefaultControllerFactory
    {
        protected override IController
            GetControllerInstance(RequestContext requestContext,
            Type controllerType)
        {
            try
            {
                if ((requestContext == null) || (controllerType == null))
                    return null;

                return (Controller) ObjectFactory.GetInstance(controllerType);
            }
            catch (StructureMapException)
            {
                System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave());
                throw new Exception(ObjectFactory.WhatDoIHave());
            }
        }
    }

    public static class Bootstrapper
    {
        public static void Run()
        {
            ControllerBuilder.Current
                .SetControllerFactory(new StructureMapControllerFactory());

            ObjectFactory.Initialize(x =>
            {
                x.AddConfigurationFromXmlFile("StructureMap.xml");
            });
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
I have been working in the IT industry for some time. It is still exciting and I am still learning. I am a happy and honest person, and I want to be your friend.

Comments and Discussions