Daniel Little Coding Blog
Daniel Little Coding Blog

A blog about .net development and the web.

Daniel Little
Author

Daniel Little (lavinski) is a Brisbane based software developer.

Share


Our Newsletter


Like this blog? Get each new post as soon it's posted.

Tags


Twitter


Ninject and Singletons in the WebAPI with Scopes

Daniel LittleDaniel Little

The new Activation Blocks in Ninject are great for automatically resolving dependencies in the request scope. However they suffer from one flaw which is they don't respect Constant or Singletons in fact they ignore the scope completely!

In my application I needed a reference my dependency injection container in one of my objects. This would end up throwing Error loading Ninject component ICache at the end of the request because now I had two kernels. Not good at all however I still had hope.

Luckily there is one type of binding the ActivationBlock can't ignore. The ToMethod binding. So now I can make a small ScopedResolver class which I can then inject into my class instead.

Binding

kernel.Bind<ScopedResolver>().ToMethod(x => {
    return new ScopedResolver((IActivationBlock)x.GetScope());
});

ScopedResolver

public class ScopedResolver
{
    IActivationBlock resolver;

    public ScopedResolver(IActivationBlock resolver)
    {
        this.resolver = resolver;
    }

    public T TryGet<T>()
    {
        return resolver.TryGet<T>();
    }

}
Daniel Little
Author

Daniel Little

Daniel Little (lavinski) is a Brisbane based software developer.

Comments