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.
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.
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With