3

I was trying to solve this for entire morning but seems that its time to ask for advice.

I have an MVC / WebApi / SignalR application. I have a service which I would like to start together with web application. And I would like this service to be injected. So this is what I am trying to do:

public static class NinjectWebCommon 
{
   ...

   private static void RegisterServices(IKernel kernel)
    {
        GlobalHost.DependencyResolver = new Microsoft.AspNet.SignalR.Ninject.NinjectDependencyResolver(kernel); 

        kernel.Bind<PricingService>().ToSelf().InSingletonScope();
    }
}

public class Application : HttpApplication
{
    protected void Application_Start()
    {
        ...
        PricingService pricingService = DependencyResolver.Current.GetService<PricingService>();
    }
}

My problem is that the pricingService variable is null.

According to this post this pattern should work but it does not. May be there is an influence from SignalR dependency resolver, but I am not really sure.

At the same time, when I'm using a constructor injection inside WebApi controller, injection works fine.

public class MyController : ApiController
{
    private readonly PricingService _pricingService;

    public MyController (PricingService pricingService)
    {
        _pricingService = pricingService;
    }
}

Any help would be highly appreciated.

Community
  • 1
  • 1
user1921819
  • 3,290
  • 2
  • 22
  • 28
  • 1
    Make sure that your DependencyResolver.Current in Application_Start is an instance of NinjectDependencyResolver. If it is not, make sure that you've got your configuration in the right place/right time in the application start up process. – Steve Lillis Dec 10 '14 at 10:07
  • Steve, thanks for the prompt answer. DependencyResolver.Current is NOT an instance of NinjectDependencyResolver. As for initialization, I do not register Resolver myself. I am using a Ninject.MVC3 package and I was under impression that this would be done automatically (somewhere). I've checked that the method RegisterServices of NinjectWebCommon class is called before Application_Start. Do I need to do some extra initialization manually? – user1921819 Dec 10 '14 at 10:32

1 Answers1

4

Thanks to Steve's comment I was able to resolve the issue.

The part that was missing is registiring a NinjectDependencyResolver in MVC infrastructure:

private static void RegisterServices(IKernel kernel)
{
    DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
    ...
}

After doing so the instance of DependencyResolver.Current changed to NinjectDependencyResolver.

Unfortunatelly this was not the end. I've got a System.EntryPointNotFoundException when trying to call DependencyResolver.Current.GetService<PricingService>(). But this was easily resolved with the help of this discussion.

Community
  • 1
  • 1
user1921819
  • 3,290
  • 2
  • 22
  • 28