This is my first time using Ninject and I'm facing some problems with my MVC 4 application.
I created a class called IocConfig
at App_Start folder in my Presentation Layer.
IocConfig class
public class IocConfig
{
public static void ConfigurarDependencias()
{
IKernel kernel = new StandardKernel();
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(kernel));
kernel.Bind<IReceitaRepository>().To<SqlReceitaRepository>();
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}
}
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory(IKernel kernel)
{
ninjectKernel = kernel;
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
return (controllerType == null) ? null : (IController)ninjectKernel.Get(controllerType);
}
}
public class NinjectDependencyResolver : IDependencyResolver
{
private readonly IResolutionRoot _resolutionRoot;
public NinjectDependencyResolver(IResolutionRoot kernel)
{
_resolutionRoot = kernel;
}
public object GetService(Type serviceType)
{
return _resolutionRoot.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _resolutionRoot.GetAll(serviceType);
}
}
And after read the thread ASP.NET MVC 4 + Nunject MVC 3, I'm trying to implement the same solution proposed by @JereJones, but I got the following error at the line below
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
return (controllerType == null) ? null : (IController)ninjectKernel.Get(controllerType);
}
Error
Error activating ISession
No matching bindings are available, and the type is not self-bindable.
Activation path:
3) Injection of dependency ISession into parameter session of constructor of type SqlReceitaRepository
2) Injection of dependency IReceitaRepository into parameter repositorio of constructor of type HomeController
1) Request for HomeController
Suggestions:
1) Ensure that you have defined a binding for ISession.
2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.
3) Ensure you have not accidentally created more than one kernel.
4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.
5) If you are using automatic module loading, ensure the search path and filters are correct.