Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection Best Practices

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??
like image 472
Jeffrey Cameron Avatar asked Oct 29 '09 11:10

Jeffrey Cameron


2 Answers

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.

like image 197
Mark Seemann Avatar answered Oct 25 '22 09:10

Mark Seemann


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.

like image 44
flukus Avatar answered Oct 25 '22 10:10

flukus