NInject ChildKernel

I’ve been working on an application which is basically a glorified scheduler. Within it I have the concept of projects which are made up triggers, tasks etc. So we have a parent child relationship going on between the project and the child elements, the triggers etc.

One problem I came across was that the application holds a StandardKernel (as one might expect) and injects dependencies etc. into the projects, triggers and tasks but I wanted to use the same mechanism to allow me to inject the current instance of a project into the children, i.e. the triggers and tasks could (if they wanted) get access to the parent project instance.

Obviously if I add the project to the application wide kernel, all triggers and tasks would get a project object, but not necessarily the project which acts as their parent (actually it’d probably fail to allow me to resolve to multiple instances of a project anyway). Of course I could pass the instance of the project to each trigger or task at construction or explicitly calling the relevant method/property, but I wanted to reuse the NInject mechanisms so as to keep a standard way of injecting objects into this application.

Enter the ChildKernel. A Ninject extension class available via GitHub.

Using the ChildKernel we can create a new kernel, which (if you like) inherits the bindings from a parent kernel and then we add further bindings specific to it’s use, as per

ChildKernel child = new ChildKernel(kernel);
child.Bind<IProject>().ToMethod(_ => currentProject);

kernel would be our StandardKernel acting as the parent kernel.

Now we simply Get or Inject using this child kernel and if a dependency is not resolved using the child, it is passed to the parent kernel to resolve.