Using IOC container as dependency converter for MVC5 throws "cannot instantiate interface"
I'm trying to just use an IOC container (ninject currently) as a dependency transformer for MVC5. This used to work in MVC4, visual studio 2012, but now with VS2013 and MVC5, I just can't get the resolver to inject the dependency into my controller. This is not the case for ninject, I tried SimpleInjector and Unity too - same error
I just want to be able to inject this class into my home controller.
public interface ITest
{
void dummyMethod();
}
public class Test : ITest
{
public void dummyMethod()
{
};
}
This is the ID of the dependencies
public class NinjectDependencyResolver : IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver()
{
kernel = new StandardKernel();
AddBindings();
}
public object GetService(Type serviceType)
{
return kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return kernel.GetAll(serviceType);
}
private void AddBindings()
{
kernel.Bind<ITest>().To<Test>();
}
}
This is global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
DependencyResolver.SetResolver(new NinjectDependencyResolver());
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
and this is my HomeController
public class HomeController : Controller
{
public ActionResult Index(ITest test)
{
return View();
}
}
but when i run this i keep getting
Server Error in '/' Application.
Cannot create an instance of an interface.
I also tried to create a completely new project (MVC 5) - same error
I tried MVC5 and then upgraded to 5.2.2 as well. Same error
Any help is greatly appreciated. I think the resolver is never called for some reason, although if I put a breakpoint at
kernel.Bind<ITest>().To<Test>();
it stops there ... I don't know what's going on :(
source to share
You usually cannot enter parameters into your actions.
You need to inject your dependencies into your constructor constructor:
public class HomeController : Controller
{
private readonly ITest test;
public HomeController(ITest test)
{
this.test = this;
}
public ActionResult Index()
{
//use test here
return View();
}
}
source to share