Where should I do Injection with Ninject 2+ (and how do I arrange my Modules?)

I don’t know NInject, but unless it works vastly different than Windsor, StructureMap etc. the answers tend to stay the same, as there are some common DI patterns. With that in mind:

The first thing to realize is that DI isn’t tied to a particular framework such as NInject or Windsor. It is a set of techniques and design patterns to follow. You can do DI manually using so-called Poor Man’s DI, but obviously it gets much better with a DI Container.

Why is this relevant? It is relevant because once you realize this, the corollary is that the vast majority of your application’s code should have no knowledge of the DI Container whatsover.

So where do you use the DI Container? It should only be used in a Composition Root, which in your case would correspond to Global.asax. You can read a bit more about this in this SO answer – although that question is about Windsor, the principle remains the same.

How about your unit tests then? They should be completely ignorant of the DI Container as well. See this other SO answer for more details.

DI can be achieved in your library with copious use of Constructor Injection. You don’t need to reference any DI Container to do that, but it makes life a lot easier if you use a DI Container to resolve all dependencies from the Composition Root.

Leave a Comment