tags:

views:

188

answers:

2

I have written a COM component in unmanaged C++ to provide customers access to our database. When using it from an unmanaged language the database connections are correctly cleaned up as the objects go out of scope. I recently tried using it from VB.NET and discovered that the COM objects are not being destroyed. Scattering calls to System.Runtime.InteropServices.Marshal.ReleaseComObject fixes the problem, but I'd like to find a simpler and exception safe solution since this COM object is designed for customer use.

It appears that the correct solution is to have the managed objects implement IDisposeable so the using statement can be used, automatically calling Dispose when the object is not longer required.

How do I go about implementing IDisposeable for a subset of my objects? Several of the objects that require disposing are not co-creatable but are returned by other functions.

+2  A: 

Madness lies that way. You'll be better off wrapping your COM objects in type safe .Net wrappers that implement IDisposable (if you like), or use the normal methods of .Net garbage collection to clean themselves up.

1800 INFORMATION
Is there a better way to ensure the database connections are closed other than to use IDisposable? I'd really like to ensure that all the COM objects are cleaned up as currently there is a crash on exit when my caches in the COM component are destroyed in DllMain. If the COM objects were released the caches would be empty.
Stephen Nutt
+1  A: 

You could go with the .NET wrappers as 1800 INFORMATION suggests, then remember to always use them with a using statement as you said:

using( var connection = GetDisposableConnection() )
{
    //do stuff
}

If this doesn't work because something wasn't being released correctly, you can insert these lines when shutting down:

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Ant
Thanks for the tip of calling WaitForPendingFinalizers, I had not come across that before.
Stephen Nutt
No problem - glad to have helped.
Ant