代码之家  ›  专栏  ›  技术社区  ›  Korbin

没有ASP DI容器的控制器的构造函数参数。NET MVC

  •  9
  • Korbin  · 技术社区  · 17 年前

    除了使用依赖注入容器之外,有人有关于如何创建具有参数的控制器的代码示例吗?

    我看到了很多使用StructureMap等容器的示例,但如果你想自己传递依赖类,就什么都没有了。

    3 回复  |  直到 17 年前
        1
  •  11
  •   Ben Scheirman    17 年前

    一种方法是创建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());
        }
    
        2
  •  16
  •   Craig Stuntz    17 年前

    你可以使用穷人的依赖注入:

    public ProductController() : this( new Foo() )
    {
      //the framework calls this
    }
    
    public ProductController(IFoo foo)
    {
      _foo = foo;
    }
    
        3
  •  1
  •   Matt Hinze    17 年前

    您可以创建一个IModelBinder,从工厂启动实例,或者,是的,从容器启动实例。 =)