没有用于ASP.NET MVC的DI容器的控制器的构造函数参数
时间:2020-03-06 14:36:40 来源:igfitidea点击:
没有人有任何代码示例,说明如何创建具有使用依赖注入容器以外的参数的控制器?
我看到大量使用诸如StructureMap之类的容器的示例,但是如果我们想自己传递依赖项类,则什么也没有。
解决方案
我们可以使用穷人的依赖注入:
public ProductController() : this( new Foo() )
{
//the framework calls this
}
public ProductController(IFoo foo)
{
_foo = foo;
}
我们可以创建一个IModelBinder来启动工厂或者容器中的实例。 =)
一种方法是创建一个ControllerFactory:
public class MyControllerFactory : DefaultControllerFactory
{
public override IController CreateController(
RequestContext requestContext, string controllerName)
{
return [construct your controller here] ;
}
}
然后,在Global.asax.cs中:
private void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(
new MyNamespace.MyControllerFactory());
}

