Derik Whittaker

Syndication

News


Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
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 -----]


Posted 08-15-2008 7:48 AM by Derik Whittaker

[Advertisement]

Comments

Dew Drop - August 15, 2008 | Alvin Ashcraft's Morning Dew wrote Dew Drop - August 15, 2008 | Alvin Ashcraft's Morning Dew
on 08-15-2008 9:43 AM

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

DotNetKicks.com wrote Setting up IoC/DI for your Controllers in ASP.Net MVC
on 08-15-2008 11:01 AM

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

Jimmy Bogard wrote re: Setting up IoC/DI for your Controllers in ASP.Net MVC
on 08-15-2008 12:41 PM

There's also a nice StructureMapControllerFactory in MVCContrib btw.

Derik Whittaker wrote re: Setting up IoC/DI for your Controllers in ASP.Net MVC
on 08-15-2008 12:54 PM

@Jimmy,

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

ASP.NET MVC Archived Blog Posts, Page 1 wrote ASP.NET MVC Archived Blog Posts, Page 1
on 08-16-2008 11:26 AM

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

Jak Charlton wrote re: Setting up IoC/DI for your Controllers in ASP.Net MVC
on 08-18-2008 2:40 AM

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.

PK wrote re: Setting up IoC/DI for your Controllers in ASP.Net MVC
on 09-13-2008 5:25 AM

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-

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)