Ninject: Registering an already created instance with Ninject?

Dependency InjectionNinjectNinject 2

Dependency Injection Problem Overview


Can anyone tell me if i can register an already created instance of a class with Ninject so that it will use this instance everytime it needs injecting?

I suppose you can call it a singleton but I have the instance already created. All the documentation points to creating new instances of a class.

Dependency Injection Solutions


Solution 1 - Dependency Injection

You can use the ToConstant method which takes an already existing instance and registers it as singleton.

var kernel = new StandardKernel();
kernel.Bind<MyClass>().ToConstant(myClassInstance);

If you want to something more complex you can use the ToMethod (where you can use a Func to get your instance) combined with the InSingletonScope

var kernel = new StandardKernel();
kernel.Bind<MyClass>().ToMethod(context => myClassInstance).InSingletonScope();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartinView Question on Stackoverflow
Solution 1 - Dependency InjectionnemesvView Answer on Stackoverflow