Ninject.MVC3, Nuget, WebActivator oh my

前端 未结 2 1342
攒了一身酷
攒了一身酷 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:24

    Steps:

    1. Create a new ASP.NET MVC 3 project
    2. Install the NuGet package from the Package Console: Install-Package Ninject.MVC3
    3. In HomeController:

      public class HomeController : Controller
      {
          private readonly ITestService _service;
          public HomeController(ITestService service)
          {
              _service = service;
          }
      
          public ActionResult Index()
          {
              ViewBag.Message = _service.GetMessage();
              return View();
          }
      }
      
    4. In App_Start/NinjectMVC3.cs:

      private static void RegisterServices(IKernel kernel)
      {
          kernel.Bind<ITestService>().To<TestService>();
      }       
      
    0 讨论(0)
  • 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<ITestService>() to grab an instance:

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

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

    0 讨论(0)
提交回复
热议问题