9

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.

David Basarab
  • 70,191
  • 42
  • 128
  • 155
Korbin
  • 1,768
  • 2
  • 18
  • 29

3 Answers3

17

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
  • 124,853
  • 12
  • 249
  • 270
13

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
  • 39,872
  • 21
  • 100
  • 136
1

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

Matt Hinze
  • 13,494
  • 3
  • 33
  • 40