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

Kor*_*bin 9 .net c# asp.net-mvc

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

我看到很多样本都使用像StructureMap这样的容器,但是如果你想自己传递依赖类,那就没什么了.

Cra*_*ntz 17

一种方法是创建一个ControllerFactory:

public class MyControllerFactory : DefaultControllerFactory
{
    public override IController CreateController(
        RequestContext requestContext, string controllerName)
    {
        return [construct your controller here] ;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,在Global.asax.cs中:

    private void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes(RouteTable.Routes);
        ControllerBuilder.Current.SetControllerFactory(
            new MyNamespace.MyControllerFactory());
    }
Run Code Online (Sandbox Code Playgroud)


Ben*_*man 13

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

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

public ProductController(IFoo foo)
{
  _foo = foo;
}
Run Code Online (Sandbox Code Playgroud)