Control Life of aggregated object

  • Thread starter Thread starter Tony Maresca
  • Start date Start date
T

Tony Maresca

I have a general question on how to best go about
controlling the lifetime of an aggregated object.

public class Contained : IDisposable
{
public void Dispose()
{
// cleanup
}
}

public class MyContainer : IDisposable
{
public void Dispose()
{
m_Contained.Dispose();
}

public MyContained Contained
{
get
{
return m_Contained;
}
}
private Contained m_Contained = new Contained();

}

When a client references the Contained property, I want
to prevent them from disposing the returned instance.

BTW, let's assume that I don't own Contained, it is
class from another library, which I'm consuming. Let's
further assume that Contained may be sealed.
 
You do do some kind of reference counting.
The best way is to provide no accessor for the contained disposible object,
just helper methods to invoke necessary methods of it:

public class MyContainer : IDisposable
{
public void Dispose()
{
m_Contained.Dispose();
}

public void Foo()
{
m_Contained.Foo();
}

private Contained m_Contained = new Contained();
}
 
Back
Top