What is a good approach to encapsulate the creation and finalization of an object?
<p>I am using a third party assembly with a bunch of classes, organized in a hierarchical way. They have private constructors and get instantiated by invoking a <code>CreateXxx()</code> method on an instance of another class one level higher. On the top of the hierarchy, a singleton class is used. For example, application code looks something like this:</p>

<pre><code>TopClass top = TopClass.GetInstance();
SecondLevelClass secondLevel = top.CreateSecondLevelElement();
ThirdLevelClass thirdLevel = secondLevel.CreateThirdLevelElement();
</code></pre>

<p>Similarly, finalization is done using a <code>DeleteXxx()</code> method, which has to happen on the same object used for <code>CreateXxx()</code>.</p>

<p>I will not go into the reasons why this particular approach was taken. However, I would like to encapsulate the creation for these classes with my own set of classes that do have public constructors, such that the code will look better, like this:</p>

<pre><code>// No TopClass anymore, see explanation below
MySecondLevelClass secondLevel = new MySecondLevelClass();
MyThirdLevelClass thirdLevel = new MyThirdLevelClass(secondLevel);
</code></pre>

<p>My initial approach was for the <code>MyXxx</code> classes to invoke the relevant <code>CreateXxx()</code> method in the constructor and maintain a reference to the result. Also, a reference to the constructor parameter is required in order to invoke the <code>DeleteXxx()</code> method on at finalization time. For that, I was thinking about implementing <code>IDisposable</code> and invoke <code>DeleteXxx()</code> inside <code>Dispose()</code>.</p>

<p>With this approach, the <code>TopClass</code> has become superfluous for the application developer, because its single purpose was the creation and destruction of SecondLevelClass instances. This now happens under the hood inside the <code>MySecondLevelClass</code> constructor.</p>

<p>All in all, I think this is technically sound. The only problem I run into is the fact that the original classes implement interfaces that have a lot of methods, which I still want to be exposed via my <code>MyXxx</code> classes. I am not looking forward to re-defining all those methods on my own classes, only to forward all invocations to the encapsulated reference to the instance of the "original" class . It would be nice if I could do something like overloading the dot operator. Or, it would be nice to tell the compiler that the encapsulated reference to the instance of the original class actually implements the interface -- sort of adding an extra indirection in the VMT.</p>

<p>Those options are not supported of course, and I have not found a way around this duplication of all methods. Does anybody have an idea of how to do this in a smarter way? Any feedback is appreciated, thanks in advance.</p>
