Search code examples
c#ninjectasp.net-web-api

Singleton Scope binding not working as intended


I am using the ninject mvc3 plugin with my web api application. I have a binding that looks like:

kernel.Bind<IFoo>().To<Foo>().InSingletonScope();

It is my interpretation that the kernal will create exactly one instance of Foo and reuse it appropriately. By putting a breakpoint in Foo's constructor, I can clearly see that it is getting called once per request, and I cannot explain why.

My only guess is that somehow a new kernel is getting created per request, but that doesn't appear to be the case, as the CreateKernel method which sets the global dependency resolver is only getting run once in the application lifetime.

I am using some code taken from this post to make ninject play nice with mvc 4. Because of framework changes, I had to make an additional wrapper that I assign to GlobalConfiguration.Configuration.DependencyResolver:

public class NinjectResolver : NinjectScope, IDependencyResolver
{
    private readonly IKernel _kernel;
    public NinjectResolver(IKernel kernel)
        : base(kernel)
    {
        _kernel = kernel;
    }
    public IDependencyScope BeginScope()
    {
        return new NinjectScope(_kernel.BeginBlock());
    }
}

What am I doing wrong?


Solution

  • I never could get it to work properly, and I am not sure why. My guess is it has something to do with MVC4 integration being a bit immature at the moment.

    As an alternative I am using:

    kernel.Bind<IFoo>().ToConstant(new Foo());

    This seems to work, but I am not too happy with it.