Question

I am using Dependency Injection in my code (with Ninject) and thought I was doing quite well until I came across a performance problem that was caused by a misunderstanding of where DI containers fit into your code. There seems to be a lot of information on how to use DI frameworks but not too much on where not to use them or how best to use them (at least that I could find)

I thought I would write out what I thought were some best practices and see if other people agree with me and what other best practices people can came up with.

  • Use one kernel per application or AppDomain
  • Use the DI container for long-lived Singleton objects only, use factories (or other methods) for short-lived transient objects)
  • Prefer Constructor Injection over Property or Field injection
  • Request objects, don't build them
  • others?? pointers to good blog entires/articles??
Was it helpful?

Solution

Here's a short list of the most important points (some of which also appear in the OP):

  • Code should be unaware of which DI Container (if any) is used
  • Compose the entire application in the root of the application (the Composition Root)
  • Favor Constructor Injection

I can't say I agree with your point about Singleton vs. Transient objects. The whole point of DI is that an external mechanism (such as a DI Container) determines the life-time of any given dependency, not someone else, so you need to have all dependencies managed by the DI Container.

OTHER TIPS

Use the DI container for long-lived Singleton objects only, use factories (or other methods) for short-lived transient objects)

But do use DI to inject the factories into where there needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top