I’m currently learning Ninject and dependency injection and in my current set-up I’m passing IKernel into places so other classes can instantiate certain classes or grab factory instances.
Currently I’ve got my factories bound as singletons, and passing IKernel into an object then doing _kernel.Get<ISomethingFactory>().CreateSomething() seems like it could be a bit of a code-smell and simply turning Ninject into a glorified service locator.
Also, my factories are being passed IKernel so they can resolve the bound implementation of the respective interface they create.
My questions are:
-
Is it permissible for factories to function in this way, or should the factory simply instantiate the concrete type itself?
-
Instead of passing IKernel all over the place, should I be favouring passing the factories / other services through the constructor?
I prefer not to.. but that’s just me.
Also, I don’t roll my own factories.. I use Ninjects Factories extension. You can find it here:
https://github.com/ninject/ninject.extensions.factory
Basically, you create your bindings like normal, but then you create interfaces for factories (assuming WinForms here):
..and bind it with the
ToFactoryextension:The factories extension doesn’t need you to define a concrete implementation of this interface.. it already knows what to do with these objects based on bindings you’ve provided (and will still instantiate anything you haven’t defined a binding for.. such as forms. Behind the scenes it creates a manager that implements this interface for you).
So then, you can do things like this:
..then in frmSettings it will inject as well:
..this is how I choose to do things. Perhaps others have better ideas (I’d be interested in hearing them too!).