3

ViewModel in my MVVM Light application has some resourse, that must be dispose when application is closing. I have CleanUp method in ViewModelLocator to do it. Where is right place in my application to call CleanUp method.

public class ViewModelLocator
{
    /// <summary>
    /// Initializes a new instance of the ViewModelLocator class.
    /// </summary>
    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

        SimpleIoc.Default.Register<MainViewModel>();
    }
    public MainViewModel Main
    {
        get
        {
            return SimpleIoc.Default.GetInstance<MainViewModel>();
        }
    }
    public static void Cleanup()
    {
        var main=SimpleIoc.Default.GetInstance<MainViewModel>();
        main.Dispose();
    }
}
public class MainViewModel:ViewModelBase, IDisposable
{

    public void Dispose()
    {
       disposableResoure.Dispose();
    }
}

2 Answers 2

1

You could use the Closing or Closed event on the MainWindow class of the Application class - probably best use the Closed event because the window will no longer be visible.

http://msdn.microsoft.com/en-us/library/system.windows.application.mainwindow(v=vs.110).aspx

Or you could use the Exit event on the Application class.

http://msdn.microsoft.com/en-us/library/system.windows.application.exit(v=vs.110).aspx

0

If you're exiting the application, then why clean up resources at all? The OS will do that when the process is torn down. You want to call Dispose() on an IDisposable when you no longer need the resource so you can clean up all the unmanaged resources. If the process is getting tossed out, then there isn't a need to call it since garbage collection isn't going to happen in the memory space after the process is gone.

I agree that Disposing of resources after your Window has gone out of "scope" to the user and is no longer needed, but the end of the process is not necessary.

Here is another way to use the Cleanup() method:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.