Constructor parameters for controllers without a DI container for ASP.NET MVC

后端 未结 3 1022
执念已碎
执念已碎 2020-12-06 02:56

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

相关标签:
3条回答
  • 2020-12-06 03:00

    You can use poor-man's dependency injection:

    public ProductController() : this( new Foo() )
    {
      //the framework calls this
    }
    
    public ProductController(IFoo foo)
    {
      _foo = foo;
    }
    
    0 讨论(0)
  • 2020-12-06 03:09

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

    0 讨论(0)
  • 2020-12-06 03:22

    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());
        }
    
    0 讨论(0)
提交回复
热议问题