Ninject.MVC3, Nuget, WebActivator oh my

前端 未结 2 1344
攒了一身酷
攒了一身酷 2021-02-01 23:41

I want to setup Ninject to do a simple test, as well as demonstrate the ease-of-setup using Nuget. I want to resolve a sample service.

public interface ITestSer         


        
2条回答
  •  一整个雨季
    2021-02-02 00:38

    Add the ITestService as a constructor parameter to your controller:

    private ITestService service;
    
    public MyController(ITestService service)
    {
       this.service = service;
    }
    
    public ActionResult Index()
    {
      ViewBag.Message = this.service.GetMessage();
      return View();
    }
    
    

    Ninject will automatically inject the ITestService into your controller. Then use the service field inside your Index method.


    Alternately, if you don't want Ninject to inject into your controller constructor, you can keep around the kernel you create, then inside your Index method, you call kernel.Get() to grab an instance:

    public ActionResult Index()
    {
      var kernel = ... // Go grab the kernel we created back in app startup.
      ITestService service = kernel.Get();
    
      ViewBag.Message = service.GetMessage();
      return View();
    }
    

    Have a look at Ninject dependency inject for controllers in MVC3.

提交回复
热议问题