Search code examples
wpfprismdesign-patternsidisposableprism-4

Wpf PRISM disposable module


I'm having a WPF application that is divided into PRISM modules.

I have a service that deals with some unmanaged resources, therefore it implements the IDisposable interface:

public class MyCacheService : IMyCacheService, IDisposable
{
    ...
}

I also have a CameraServicesModule which registers an IMyCacheService instance:

public class CameraServicesModule : IModule
{
    public CameraServicesModule(IComponentsManager manager)
    {
        this.manager = manager;
    }

    public void Initialize()
    {
       ...
       var theCacheService = new MyCacheService();
       this.manager.RegisterInstance(typeof(IMyCacheService), null, theCacheService);
    }
}

The question is: how do I dispose of the service instance? I have to do it at the application closing, but right now the MyCacheService.Dispose() doesn't get called at the application shutdown (or any other point in time).

Should the CameraServicesModule implement IDisposable, too? Like this:

public class CameraServicesModule : IModule, IDisposable
{
    public CameraServicesModule(IComponentsManager manager)
    {
        this.manager = manager;
    }

    public void Initialize()
    {
       ...
       this.theCacheService = new MyCacheService();
       this.manager.RegisterInstance(typeof(IMyCacheService), null, theCacheService);
    }

    public void Dispose()
    {
        this.theCacheService.Dispose();
    }
}

If so, the question is: how do I dispose of the module? If not, the question is: which way should I dipose the service of?

 LocalFileSystemConfigurationManager configManager = new LocalFileSystemConfigurationManager(this.PathToSettings);
 ComponentsManager compManager = new ComponentsManager(configManager, null, null);

Note: even if my module does implement IDisposable, disposing the componentsManager or configurationManager does not dispose the module.


Solution

  • OK, after consulting some senior developers I came to a conclusion that the most appropriate way to dispose of the service is to implement IDisposable on the module which creates the service instance:

    public class CameraServicesModule : IModule, IDisposable
    {
        public CameraServicesModule(IComponentsManager manager)
        {
            this.manager = manager;
        }
    
        public void Initialize()
        {
           ...
           this.theCacheService = new MyCacheService();
           this.manager.RegisterInstance(typeof(IMyCacheService), null, theCacheService);
        }
    
        public void Dispose()
        {
            this.theCacheService.Dispose();
        }
    }
    

    Though the module implements IDisposable, we can leave it as it is, without manually calling Dispose. The module should exist until the apllication works (at least in my case), so all of the allocated resources are anyway freed up at the application close.