Ivan
Ivan

Reputation: 173

Do not call Dispose of parts in dispose MEF

I ran into a problem when the application ends the container does not call the Dispose method of the parts. Application based on MEF.

When I explicitly call Dispose the container, then matod Dispose is called on the parts, but if you just close the program, the Dispose of the parts will not be called, why? How to make sure that when you close the program were caused by the Dispose method of all parts of the container MEF?

[Export(typeof(IMyClass))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class MyClass: IDisposable, IMyClass
{
    private bool disposed = false;

    public void Dispose()
    {
        Dispose(true);

        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if(!this.disposed)
        {
            if(disposing)
            {
                // Dispose managed resources.

            }

            disposed = true;
        }
    }

    ~MyClass()
    {
        Dispose(false);
    }
}

Upvotes: 0

Views: 1270

Answers (2)

Ivan
Ivan

Reputation: 173

Wim Coenen, thanks, I thought that the destruction of MEF must call Destruct on parts. I made ​​sure to work the way I need to:

public partial class MyBootstrapper : MefBootstrapper
{
   public MyBootstrapper()
   {
      App.Current.Exit += new ExitEventHandler(Current_Exit);
   }

   void Current_Exit(object sender, ExitEventArgs e)
   {
      if (this.Container != null)
         this.Container.Dispose();
   }
...

Upvotes: 0

Wim Coenen
Wim Coenen

Reputation: 66723

When I explicitly call Dispose the container, then matod Dispose is called on the parts, but if you just close the program, the Dispose of the parts will not be called, why?

Because disposing the container when you are done with it is mandatory. If your program does not call CompositionContainer.Dispose() before exiting, then that is a bug in your program.

Upvotes: 2

Related Questions