Search code examples
c#singletonninject

Ways to setup a Ninject singleton


I have a class (MyFacade) that I injected parameter(s) with Ninject:

class MyFacade
{
    IDemoInterface demo;

    public MyFacade(IDemoInterface demo)
    {
        this.demo = demo;
    }

    public void MyMethod()
    {
        Console.WriteLine(demo.GetInfo());
    }
} 

Of course, I have to setup the Ninject to inject the appropiate implementation of my parameter (IDemoInterface)

I know, I can instantiate MyFacade object by doing kernel.Get<MyFacade>(); without setting anything else. Currently my facade doesn't have an interface (because it is my only implementation, maybe I will add its interface for standard proposes)

if I want to make this facade singlenton, I know two ways: create a empty constructor and pass a parameter by doing this kernel.Get<IDemoInterface>(); or by setup Ninject like: kernel.Bind<MyFacade>().To<MyFacade>().InSingletonScope();

The second one look a better approach, but do you know any other way to setup it in a singleton way?


Solution

  • When setting up your bindings, you need to bind your dependencies. It is always better to setup your dependencies in your bindings, as opposed to doing a kernel.Get<T>() in a constructor. You are using IOC, so leverage the framework you are using to do the injection for you.

    In your second example binding, what you are missing is binding in your IDemoInterface. Your bindings should look like this:

    //bind the dependency to the implementation.
    kernel.Bind<IDemoInterface>().To<DemoInterface>();
    //since you bound your dependency, ninject should now have 
    // all the dependencies required to instantiate your `MyFacade` object.
    kernel.Bind<MyFacade>().To<MyFacade>().InSingletonScope();