I thought more about the
problem and think that the simplest solution (notice that I didn't say best) is to have a method to increment the reference count on an RCW. The idea is COM-esque, and would allow for lifetime management control for those instances where RCW objects/references are passed via method/property calls. I also thought about the idea of having the .NET runtime automatically bump the reference count in these instances, but then realized the user's code would become more complicated because there will be Marshal.ReleaseComObject calls littered throughout their code, in many cases where no strong references need to be held.
public class Test2 : IDispose
{
private SomeClass.Interop.IBar m_pIBar;
public void Test2()
{
Test1 test1 = new Test1();
m_pIBar = test1.IBar;
// The following line of code increments the RCW count to 2
System.Runtime.InteropServices.Marshal.AddRefComObject(m_pIBar);
// The following line of code decrements the RCW count to 1, leaving
// m_pIBar valid!
test1.Dispose();
}
public void Dispose()
{
if (m_pIBar != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(m_pIBar);
}
}