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.
This is the general problem of managing lifetime. The basic rule is that he who creates an object has the ownership of that instance. The owner should dispose/destroy that instance. Ownership can be passed on to someone else, which makes that 'someone else' responsible of destroying that instance.
In your case the Foo instance is not created by Bar, so bar is not responsible of disposing that instance. Since Ninject created that instance for you, it is responsible for its clean-up.
Ownership can be passed on, but this must be something explicit. A good example of explicit ownership passing is the Factory design pattern:
IFoo CreateNewFoo();
Although this method creates new IFoo
instances, it is pretty clear that he passes the ownership back to the caller.
A good example of a BAD way of passing ownership is .NET's StreamReader
class. It takes a disposable object in its constructor, but it takes ownership. Although the documentation states that the class disposes the given object, this behavior dazzles many developers, because it goes against the general rule of ownership. Microsoft finally fixed this in .NET 4.5 by adding a ctor overload that allows suppressing the disposal of the given stream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With