R – How to implement Dispose in a COM object

cominteropnet

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.

Best Answer

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.