This often puzzled me. Although I was not happy with this, I always came to the conclusion that it is better to never return an IDisposable to transition mode.
Recently, I have rephrased the question for myself: is this really an IoC problem or a problem with the .net framework? In any case, the disposal is awkward. It does not have a significant functional purpose, only a technical one. So this is more of a framework problem that we have to deal with than an IoC problem.
What I like about DI is that I can ask for a contract that provides me with functionality without worrying about the technical details. I am not the owner. There is no knowledge of in which layer it is absent. No knowledge of what technologies are needed to fulfill the contract, do not worry about life. My code looks beautiful and clean and can be checked. I can perform duties in the layers where they belong.
So, if there is an exception to this rule that requires me to organize a lifetime, let it be an exception. I love it or not. If an object that implements the interface requires me to dispose of it, I want to know about it since I started using this object as short as possible. The trick, resolving it with a child container, which will be installed some time later, may still make me keep the object alive longer than I should. The permissible lifetime of an object is determined upon registration of the object. Not according to the functionality that creates a child container and is held on it for a certain period of time.
So, while we developers have to worry about recycling (will this ever change?), I will try to introduce as few transient disposable objects as possible. 1. I am trying to make the object not IDisposable, for example, without saving disposable objects at the class level, but in a smaller area. 2. I am trying to make the object reusable so that I can use another lifetime manager.
If this is not possible, I use the factory to indicate that the user of the entered contract is the owner and should take responsibility for it.
There is one caveat: changing a contractor from unsafe to one-time will be a change. At this time, the interface will no longer be registered, but the interface to the factory. But I think this applies to another scenario. Forgetting to use a child container from now on will give memory problems. The factory approach will throw an IoC exception.
Code example:
using System; using Microsoft.Practices.Unity; namespace Test { // Unity configuration public class ConfigurationExtension : UnityContainerExtension { protected override void Initialize() { // Container.RegisterType<IDataService, DataService>(); Use factory instead Container.RegisterType<IInjectionFactory<IDataService>, InjectionFactory<IDataService, DataService>>(); } }