Disposable Class Management Dependency Injection

I am wondering how to manage an object using DI. Suppose I have a class

class Foo : IFoo, IDisposable { // ... } 

Then this class is introduced into another class.

 class Bar { public Bar(IFoo foo) { this.Foo = foo } IFoo Foo { get; set; } } 

Then I bind this in some area (in my example MVC and Ninject are used)

 this.Bind<IFoo>().To<Foo>().InRequestScope(); 

I am wondering, since the Injection Dependency framework handles the Foo life cycle, should I implement IDispoable in Bar ? I think DI manages the life cycle of Foo , so don't touch it if another class uses Foo . In addition, since a one-time object is passed to Bar as a constructor parameter, Bar does not wrap the one-time object, so it does not know how the caller Bar wants to use Foo after Bar - garbage collection. Is it correct?

+6
source share
2 answers

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

+3
source

This is a common life time management problem. The basic rule is that whoever creates the object has the right to own this instance. The owner must dispose of / destroy this instance. Property can be transferred to someone else, which makes β€œsomeone else” responsible for the destruction of this instance.

In your case, the Foo instance is not created by Bar, so bar is not responsible for deleting this instance. Since Ninject created this instance for you, it is responsible for cleaning it up.

Property can be transferred, but it must be something explicit. A good example of explicit ownership transfer is the Factory design pattern:

 IFoo CreateNewFoo(); 

Although this method creates new instances of IFoo , it is pretty clear that it transfers ownership back to the caller.

A good example of a BAD method of transferring ownership is the .NET StreamReader class. It takes a one-time object in its constructor, but it takes responsibility. Although the documentation states that the class has this object, this behavior blinds many developers because it contradicts the general rule of ownership. Microsoft finally fixed this in .NET 4.5 by adding ctor overload, which can suppress deletion of a given stream.

+3
source

All Articles