I absolutely love inversion of control, it is a best practice that I encourage developers to use in every project that they work on. However, like any great tool, dependency injection can cause serious problems if you do not fully understand it; lifetime management in particular.
As a developer you need to be cognisant of how many instances the container is constructing of your classes. You need to know when singleton is going to consume a transient or non thread safe resource. If you are not careful you can leak memory, share unsafe resources, or just make your garbage collector thrash.
Here is a series of examples regarding how to use lifetime managers in my favorite dependency injection container, Microsoft Unity.
- ResolveType
- Default Lifetime Manager
- TransientLifetimeManager
- RegisterInstance
- ContainerControlledLifetimeManager
- ExternallyControlledLifetimeManager
- ContainerControlledLifetimeManager with Multiple Keys
- RegisterType for Multiple Interfaces
- ContainerControlledLifetimeManager with Multiple Interfaces
- TransientLifetimeManager with Multiple Interfaces
- RegisterInstance Multiple Times
- RegisterInstance Multiple Times with External Lifetime Manager