I am new to MVC, i am following "PRO ASP.NET MVC 4 by Adam Freeman". I am currently working on its 6th chapter. In which i am learning how to use Ninject in MVC 4 for Dependency Injection. I have created the application as described in the book. Now i am not getting why the following Error Comes:
the type NinjectDependencyResolver does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator
Here is my Controller code:
public class HomeController : Controller
{
private Product[] products = {
new Product {Name = "Kayak", Category = "Watersports", Price = 275M},
new Product {Name = "Lifejacket", Category = "Watersports", Price = 48.95M},
new Product {Name = "Soccer ball", Category = "Soccer", Price = 19.50M},
new Product {Name = "Corner flag", Category = "Soccer", Price = 34.95M}
};
private IValueCalculator calc;
public HomeController(IValueCalculator calcParam)
{
calc = calcParam;
}
public ActionResult Index()
{
ShoppingCart cart = new ShoppingCart(calc) { Products = products };
decimal totalvalue = cart.CalculateProductTotal();
return View(totalvalue);
}
}
I have created a class named as "NinjectDependencyResolver" as below:
public class NinjectDependencyResolver : DependencyResolver
{
private IKernel kernal;
public NinjectDependencyResolver()
{
kernal = new StandardKernel();
AddBindings();
}
public object GetService(Type serviceType)
{
return kernal.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return kernal.GetAll(serviceType);
}
private void AddBindings()
{
kernal.Bind<IValueCalculator>().To<LinqValueCalculator>();
}
}
Changed the global file as below:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
DependencyResolver.SetResolver( new NinjectDependencyResolver());
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
on the "DependencyResolver.SetResolver( new NinjectDependencyResolver());" this line of i am getting the error:
The type EssentialTools.Infrastructure.NinjectDependencyResolver does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator. Parameter name: commonServiceLocator
Please help me, how can i resolve this error.
Thanks in advance.
The problem is that your
NinjectDependencyResolverdoesn't implement theIDependencyResolverinterface, but inherits from theDependencyResolverclass. TheDependencyResolverdoes not implementIDependencyResolverand this causes your own methods to be unrelated to anything MVC knows.Just change to:
But as Ufuk Hacıoğulları says, you can use the official Ninject.MVC3 NuGet package to integrate Ninject with MVC. This package is created by the developers of Ninject and depends on the Ninject core library.