ridermansb
ridermansb

Reputation: 11069

DependencyResolver.Current.GetService always returns null

According to this tutorial, to use Ninject in my Asp.net MVC 3 application , all I have to do is install package via Nuget and configure 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've tried kernel.Bind<IReCaptchaValidator>().To<ReCaptchaValidate>().InRequestScope(), but not effect!

myObject continues null

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

Upvotes: 11

Views: 22060

Answers (2)

user2173353
user2173353

Reputation: 4660

I had the same problem. On the same function, I could resolve an interface just fine, while another interface did not resolve. They were both registered!

When resolving manually, it seems that you don't get errors! Pretty funny, but I just found about!

Once I injected the interface in a controller constructor and enabled all exceptions, then I get an exception saying that there was no public constructor for my implementation!

Try that and you will most likely find the root cause.

Upvotes: 2

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93464

In the post you refer to, you were not told to use DependencyResolver, just that it's possible to use it. You shouldn't use it, as it's a well known anti-pattern.

While using the DependencyResolver directly should work, you really shouldn't do it that way.

Instead, you should use Constructor Injection, which would be to have your class take the type as a parameter of 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;
}  

Upvotes: 4

Related Questions