Saturday, February 5, 2011

Constructor parameters for controllers without a DI container for ASP.NET MVC

Does anyone have any code examples on how to create controllers that have parameters other than using a Dependency Injection Container?

I see plenty of samples with using containers like StructureMap, but nothing if you wanted to pass in the dependency class yourself.

  • You can use poor-man's dependency injection:

    public ProductController() : this( new Foo() )
    {
      //the framework calls this
    }
    
    public ProductController(IFoo foo)
    {
      _foo = foo;
    }
    
  • You can create an IModelBinder that spins up an instance from a factory - or, yes, the container. =)

    From Matt Hinze
  • Creative approach LOL. I would suspect that MS will eventually add a easier mechanism for doing this if we didn't want to depend on a third party open source codebase (DI container).

    Ben Scheirman : Why don't you want to leverage a DI container? They alleviate all the pain with resolving dependencies. It's a tiny investment in learning a tool and you can a load in return in avoiding messy constructor wiring. Windsor, StructureMap, Ninject, Spring... pick one and run with it.
    Korbin : Because some customers are opposed to using open source software. Even though Asp.net MVC is open source it's still supported by MS.
    From Korbin
  • One way is to create a ControllerFactory:

    public class MyControllerFactory : DefaultControllerFactory
    {
        public override IController CreateController(
            RequestContext requestContext, string controllerName)
        {
            return [construct your controller here] ;
        }
    }
    

    Then, in Global.asax.cs:

        private void Application_Start(object sender, EventArgs e)
        {
            RegisterRoutes(RouteTable.Routes);
            ControllerBuilder.Current.SetControllerFactory(
                new MyNamespace.MyControllerFactory());
        }
    

0 comments:

Post a Comment