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.
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());
}
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. =)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.