Possible Duplicate:
MVC3 + Ninject – How to?
In a small mvc 4 project, I’m trying to implement dependency injection using ninject.
So far, I have it working with api controllers, but I’m not having any luck with regular controllers.
I have A NinjectResolver:
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
private readonly IKernel _kernel;
public NinjectDependencyResolver(IKernel kernel)
: base(kernel)
{
_kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(_kernel.BeginBlock());
}
public override void Dispose()
{
_kernel.Dispose();
}
}
And a NinjectScope:
public class NinjectDependencyScope : IDependencyScope
{
protected IResolutionRoot ResolutionRoot;
public NinjectDependencyScope(IResolutionRoot kernel)
{
ResolutionRoot = kernel;
}
public object GetService(Type serviceType)
{
var request = ResolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
return ResolutionRoot.Resolve(request).SingleOrDefault();
}
public IEnumerable<object> GetServices(Type serviceType)
{
var request = ResolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
return ResolutionRoot.Resolve(request).ToList();
}
public void Dispose()
{
var disposable = (IDisposable)ResolutionRoot;
if (disposable != null) disposable.Dispose();
ResolutionRoot = null;
}
}
Then I set it up in my Global.asax:
var kernel = new StandardKernel();
kernel.Bind(typeof(IRepository)).To(typeof(Repository));
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
Then I inject a repository into an api controller like this:
private IRepository _repository;
public TestApiController(IRepository repository)
{
_repository = repository;
}
This works fine, but doing the same in a regular controller fails with the
“No parameterless constructor defined for this object” error.
Any ideas?
ASP.NET MVC uses a different
IDependencyResolverthan ASP.NET WebAPi namellySytem.Web.Mvc.IDependencyResolver.So you need a new
NinjectDependencyResolverimplementation for the MVC Controllers (luckily the MVC and WepAPiIDependencyResolveralmost has the same members with the same signatures, so it’s easy to implement)And then you can register it in the
Global.asaxwith: