Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ninject: Registering an already created instance with Ninject?

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.

like image 566
Martin Avatar asked Jun 04 '13 11:06

Martin


People also ask

How to implement dependency injection in c# using Ninject?

Step 1: We are creating an instance of Class StandardKernel. Step 2: Then we will load the Kernel. Step 3: Get the instance of the specific service that we want to inject. Step 4: Then inject the dependency.

Why Ninject is used?

Ninject is a lightweight dependency injection framework for . NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner.

What is a ninject module?

The Ninject modules are the tools used to register the various types with the IoC container. The advantage is that these modules are then kept in their own classes. This allows you to put different tiers/services in their own modules.

What is ninject DLL?

Ninject helps you use the technique of dependency injection to break your applications into loosely-coupled, highly-cohesive components, and then glue them back together in a flexible manner.


1 Answers

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(); 
like image 155
nemesv Avatar answered Sep 17 '22 14:09

nemesv