Howto: Disposable module

Topics: Prism v4 - WPF 4
Aug 9, 2010 at 5:54 PM
How to create a disposable module? I need my module was disposed as it uses some unmanaged resources (COM). Particularly it creates and holds a reference to ManagementEventWatcher. Now I'm getting InvalidComObjectException on application termination: "COM object that has been separated from its underlying RCW cannot be used". So I need to have some way to call ManagementEventWatcher.Stop before it'll GCed. I've tried to implement IDisposable in my module (naive), but it isn't called by Prism. How to do this?
Aug 9, 2010 at 9:40 PM

Hi,

I do not know your exact scenario, but first of all if you use unmanaged resources in your application, you might prefer to separate this in a different component (e.g. a service) to have a complete control of its disposal. Otherwise, you depend on the garbage collection and it not possible to predict when it will occur.

On the specific subject of resource management, you need to ensure that your unmanaged resources are released. The way to do this is by implementing IDisposable correctly, as it explained in the code sample from this MSDN article.

This way, you would be able to handle the component’s disposal manually, as it shown here. For example, if you opt to use a service, the call should look like the following:

using (var myService = container.Resolve<MyService>())
{ 
    ...
}

For more information on how to implement the Dispose method, you could check the following documentation sections:

Please let me know if this helps.

Fernando Antivero
http://blogs.southworks.net/fantivero

Aug 12, 2010 at 3:42 PM
Hi, thanks for your answer. I understand that I need IDisposable for my unmanaged resource wrapper. If I can just dispose my component/service then there's no any issue connected with Prism. My unmanaged component's lifetime is equal my module's lifetime. So I can't use using. I don't know when module will die. The component must be disposed right before application shutdown. And the app can't do this, only module can do this as it only one who knows about the component. So it'd be nice if Prism provides some mechanism to notify modules about shutdown.
Oct 28, 2010 at 2:14 PM

This is how I'm doing it in my bootstrapper, it seems to work fine for my application. My modules and services are correctly being disposed (verified through logging).

        protected override void ConfigureContainer()
        {
            base.ConfigureContainer();

            // Ensure we properly dispose of objects in the container at application exit
            Application.Current.Exit += (sender, e) => this.Container.Dispose();
        }