I\'m currently learning how to use Autofac, and I\'m stuck with disposing IDisposable
objects deterministically. Let me first present the situation before I\'ll sta
The other answers here are insightful, but have a problem. In both cases, if Apple has other dependencies that need disposal, correct cleanup won't happen.
Autofac 2 provides a new feature to help here, called "owned instances". I noticed that your registration code is Autofac 1.4, so if you're unable to upgrade let me know (there are other, less transparent, ways to do this.)
Register Apple as usual (not externally owned):
builder.RegisterType().As();
Declare AppleFactory as:
public delegate Owned AppleFactory();
In Autofac 2, you do not need to call RegisterGeneratedFactory() anymore - this is automatic.
Then, in HorseKeeper, feed the horse like this:
public void FeedHorse()
{
using (var apple = appleFactory())
{
horse.Eat(apple.Value);
}
}
(Note the .Value property to get the underlying IApple.
At the end of the using block the apple, plus all of its dependencies, will be cleaned up.
Any other components that use IApple directly (as dependencies) will get the usual behaviour.