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
Steps:
Install-Package Ninject.MVC3
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();
}
}
In App_Start/NinjectMVC3.cs
:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<ITestService>().To<TestService>();
}
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.