views:

491

answers:

4

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.

+2  A: 

You can use poor-man's dependency injection:

public ProductController() : this( new Foo() )
{
  //the framework calls this
}

public ProductController(IFoo foo)
{
  _foo = foo;
}
Ben Scheirman
A: 

You can create an IModelBinder that spins up an instance from a factory - or, yes, the container. =)

Matt Hinze
A: 

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).

Korbin
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.
Ben Scheirman
Because some customers are opposed to using open source software. Even though Asp.net MVC is open source it's still supported by MS.
Korbin
+5  A: 

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());
    }
Craig Stuntz