Ninject.MVC3, Nuget, WebActivator oh my

巧了我就是萌 提交于 2019-12-02 20:39:39

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.

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>();
    }       
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!