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 informatio开发者_如何学Pythonn 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??
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.
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.
精彩评论