Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NInject: Where do you keep your reference to the Kernel?

I'm using NInject on a new web application and there are two things that are unclear to me:

  1. Don't I need to keep a reference to the Kernel around (Session/App variable) to insure that GC doesn't collect all my instances? For example, if I specify .Using() and then the Kernel object gets collected, aren't all my "singletons" collected as well?

  2. If I do need keep a reference to a Kernel object around, how do I allow the arguments passed in to WithArguments() to change or is that not possible.

like image 902
JC Grubbs Avatar asked Feb 26 '09 15:02

JC Grubbs


People also ask

What is kernel in ninject?

In Ninject the Kernel is the component that controls everything. We can directly bind the interfaces with implementations in the Kernel or we can pass them wrapped as modules. Whenever we need any implementation of the mapped interface we can get it right away from the Kernel.

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.

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.


1 Answers

It's true that you don't want to pass around the kernel. Typically, in a web app, I store the kernel in a static property in the HttpApplication. If you need a reference to the kernel, you can just expose a dependency (via constructor argument or property) that is of the type IKernel, and Ninject will give you a reference to the kernel that activated the type.

If you use WithArguments() on a binding, they will be used for all activations. If you use IParameters, they will only be used for that activation. (However, if the service you're activating has a re-usable behavior like Singleton, it won't be re-activated even if you pass different IParameters.)

like image 109
Nate Kohari Avatar answered Sep 17 '22 19:09

Nate Kohari