开发者

Ninject: Controller Constructor with int argument

开发者 https://www.devze.com 2022-12-27 19:35 出处:网络
How can you instantiate a Controller that has an int argument? Using Ninject.. My HomeController has a constructor like this:

How can you instantiate a Controller that has an int argument? Using Ninject..

My HomeController has a constructor like this:


  private int _masterId;
  Public HomeController(int masterId){
       _masterId = masterId;
}

I created a controller factory like this:


public class NinjectControllerFactory : DefaultControllerFactory
    {
        IKernel kernel = new StandardKernel(new ExampleConfigModule());

        pr开发者_如何学编程otected override IController GetControllerInstance(Type controllerType)
        {

            return controllerType == null ? null
                                          : (IController)kernel.Get(controllerType, 1);

        }

    }


I'm not sure if this would work with Ninject 1.0, but does work with 2.0

var controller = kernel.Get<IController>(new ConstructorArgument("masterId", 1)); 

However it's probably not too good idea to pass arguments to constructor manually when using IoC container.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号