captncraig captncraig -4 years ago 77
C# Question

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:


It is my interpretation that the kernal will create exactly one instance of
and reuse it appropriately. By putting a breakpoint in
'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
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

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download