DependencyResolver.Current.GetService always returns null

According to this tutorial , to use Ninject in my MVC 3 application for Asp.net, all I need to do is install the package through Nuget and configure the dependencies.

Follow these steps

Install package-Ninject.MVC3

In NinjectMVC3.cs

private static void RegisterServices(IKernel kernel) { kernel.Bind<IReCaptchaValidator>().To<ReCaptchaValidate>(); } 

In controller

 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Registe(RegisterModel model) { var myObject = DependencyResolver.Current.GetService<IReCaptchaValidator>(); //always null } 

myObject always returns null.

I tried kernel.Bind<IReCaptchaValidator>().To<ReCaptchaValidate>().InRequestScope() , but not the effect!

myObject continues null

In this post here at StackOverflow, I was told to use DependencyResolver.Current.GetService(TYPE) to retrieve an instance of an object.

+8
c # dependency-injection asp.net-mvc-3 ninject
source share
1 answer

In the message you are referring to, you were not told to use DependencyResolver, just to be able to use it. You should not use it, as it is a well-known anti-pattern.

While using DependencyResolver directly should work, you really shouldn't.

Instead, you should use Constructor Injection, which would have your class take a type as a parameter to your constructor.

 public class MyController : Controller { IReCaptchaValidator _validator; public MyController(IReCaptchaValidator validator) { _validator = validator; } } 

Then in your method:

 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Registe(RegisterModel model) { var myObject = _validator; } 
+8
source share

All Articles