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
If you sometimes want to manage the lifetime of Apple instances yourself, and sometimes let the container handle it, then you can define two interfaces:
public IApple
{
void Consume();
}
public IDisposableApple : IApple, IDisposable
{
}
And then register the class twice:
builder.RegisterType().As();
builder.RegisterType().As().ExternallyOwned();
You can then inject a DisposableAppleFactory into classes that need to create and dispose apples.
For classes which just need an apple with the same lifetime as the container, you inject IApple instead.
However, the fact that you need both may indicate that you are mixing newables and injectables. Apple may simply be a "newable" object, i.e. one that doesn't need to be managed by the IoC container.