Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing Disposable classes Dependency Injection

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?

like image 580
Michael Avatar asked Dec 06 '12 15:12

Michael


2 Answers

Yes your assumptions are correct. Ninject will dispose the object for you.

like image 81
Remo Gloor Avatar answered Sep 28 '22 00:09

Remo Gloor


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.

like image 44
Steven Avatar answered Sep 28 '22 00:09

Steven