Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Derik Whittaker

Thoughts on Software Development, .Net, OOP, Design Patterns and all things cool



Setting up IoC/DI for your Controllers in ASP.Net MVC

One of the really great things about the ASP.Net MVC framework is how extendable it is.  One area of extension is in the area of controller creation.  The framework allows you to replace the default ControllerFactory with your own factory and because of this we can incorporate Inversion of Control/Dependency Injection (IoC/DI) into our controller.

Setting up our project for this is very simple and requires very little code. 

1) Creating our IoCControllerFactory
We need to create a new factory that will replace the default factory used by the MVC framework.

    public class IoCControllerFactory : DefaultControllerFactory 
    {
        protected override IController GetControllerInstance(Type controllerType)
        {
            // if you need more robust logic, add it now
            return (Controller) ObjectFactory.GetInstance( controllerType );
        }
    }

2) Overriding the default ControllerFactory
In order to use our custom factory, we need to set it to the default factory via our Global.asax file.  This logic should be put into Application_Start() method

ControllerBuilder.Current.SetControllerFactory( new IoCControllerFactory() );

 

3) Setting up our IoC/DI container
In order to have StructureMap work we need to wire up all of our dependencies.  This could be done here inside (directly) our Global.asax file, but I would suggest putting it into its own class that is just called via the Application_Start() method

StructureMapConfiguration.ForRequestedType<ISomeUsefulService>>().
                TheDefaultIsConcreteType<SomeUsefulService>();

The ISomeUsefullService and SomeUsefulService classes are your own classes that will be injected into our controller.

4) Modifying our Controllers for IoC/DI
We now need to modify our controllers to accept the various dependences that will be injected.

       public HomeController( ISomeUsefulService someUsefulService)
        {
            SomeUsefulService = someUsefulService;
        }

There you go, it is pretty easy and simply to setup an MVC web project to use IoC/DI in its controllers.

Till next time,

[----- Remember to check out DimeCasts.Net -----]



Comments

Dew Drop - August 15, 2008 | Alvin Ashcraft's Morning Dew said:

Pingback from  Dew Drop - August 15, 2008 | Alvin Ashcraft's Morning Dew

# August 15, 2008 9:43 AM

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# August 15, 2008 11:01 AM

Jimmy Bogard said:

There's also a nice StructureMapControllerFactory in MVCContrib btw.

# August 15, 2008 12:41 PM

Derik Whittaker said:

@Jimmy,

You are 100% correct.  I did fail to mention anything about MVCContrib and that not done with intent.

# August 15, 2008 12:54 PM

ASP.NET MVC Archived Blog Posts, Page 1 said:

Pingback from  ASP.NET MVC Archived Blog Posts, Page 1

# August 16, 2008 11:26 AM

Casey Charlton said:

I was going to post something similar last week - so thanks you saved me the effort :)

I looked at MVCContrib, but haven't used it as I want only a few things it offers, and there are hundreds I won't need and don't need cluttering our codebase right now. The way to use Windsor as my controller factory was the real thing I pulled from its codebase.

That alone has simplified the whole application we are working on massively over webforms.

# August 18, 2008 2:40 AM

PK said:

How do you wire up the TEST project (eg. MSTest) to use the StructureMap 'Registry' ?

I've created a Registry file for my DataAccess project and another for my Services Project.

My MVC project calls both of these registries in the global.asax.

But with my MSTests, i can do this in the TestInitialize .. but my objects are always null :(

eg.

   [TestClass]

   public class TestBase

   {

       protected IUserRepository UserRepository { get; private set; }

       protected IAuthenticationService AuthenticationService { get; private set; }

       [TestInitialize]

       public void Startup()

       {

           StructureMapConfiguration.AddRegistry(new DataAccessRegistry());

           StructureMapConfiguration.AddRegistry(new ServicesRegistry());

       }

   }

What is missing, here?

cheers!

-PK-

# September 13, 2008 5:25 AM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add

About Derik Whittaker

Derik is a .Net Developer/Architect specializing in WinForms working out the northern suburbs of Chicago. He is also believer and advocate for Agile development including SCRUM, TDD, CI, etc.

When Derik is not writing code he can be found spending time with his wife and young son, climbing on his bouldering wall, watching sports (mostly baseball), and generally vegging out. Check out Devlicio.us!

Our Sponsors

Red-Gate!