I’m wondering how to manage an object using DI. Suppose I have a class
class Foo : IFoo, IDisposable
{
// ...
}
Then this class is injected into another class
class Bar
{
public Bar(IFoo foo)
{
this.Foo = foo
}
IFoo Foo { get; set; }
}
Then I bind this in some scope (my example uses MVC and Ninject)
this.Bind<IFoo>().To<Foo>().InRequestScope();
I’m wondering, since the Dependency Injection framework handles the lifecycle of Foo, should I implement IDispoable in Bar? My thought is that DI is managing the lifecycle of Foo, so don’t touch it, in case another class is using Foo. Also, since the disposable object is passed into Bar as a constructor parameter, Bar doesn’t wrap a disposable object, so it doesn’t know how the caller of Bar wants to use Foo after Bar is garbage collected. Is this right?
Yes your assumptions are correct. Ninject will dispose the object for you.