I force GC to do a clean up
If MEF still has references to the objects, then obviously this doesn't do anything. If the objects have become garbage, then the garbage collector will automatically collect them - asking it to do that explicitly is just a hint that might be ignored. Either way, this is not necessary.
I put a logging mechanism in destructor for tracing, and objects are destroyed only after the application is closed. Can I assume MEF has created other references to those objects ?
MEF will hold references to created objects so that it is able to repeatedly return the same reference when you ask for an export. To ask MEF to abandon these references, you should call CompositionContainer.Dispose
. Obviously you cannot reuse the container any more after that, though you could create a new one.
MEF is also the owner of any IDisposable
objects it creates. This means that when you dispose the container, it will call Dispose
on any such objects before abandoning the reference.
It is preferable to rely on calls to Dispose
to perform cleanup, rather than to use finalizers. There is no guarantee that finalizers are run at all.
edit:
I need to destroy the object after using it. But I don't want to destroy the container. I want MEF as a factory for creating new instances of asking part, and the caller should be capable of destroying the object when he doesn't need anymore. Can you help with this ?
This is what ExportFactory is for. (It was formerly called PartCreator
). Unfortunately it is not yet available in .NET 4, unless you use Silverlight. You can use the preview releases from codeplex to already give it a try.
If you don't want to use the preview releases of MEF, you might be able to implement something like ExportFactory
yourself by creating factory classes that wrap the container and by using its GetExport
and ReleaseExport
methods to acquire and release objects. Don't forget to set a PartCreationPolicy
if you need to create multiple instances of the same part.
edit 2:
I somehow missed that you were already using ExportFactory
all along. You simply need to call ExportLifeTimeContext.Dispose
when you're done with the object!