Using Ninject and MVVMLight. Using a TransientScope binding to viewmodel.
When the view is gone, the viewmodel drops out of scope.
What is the trigger to cleanup my viewmodel…I have some registered events that need to be unregistered.
I can use a EventToCommand on the view unloaded event, but I’d like to learn how to do it the Ninject MVVMLight way 🙂 There are zero examples that I can find anywhere, including documentation.
ViewModelLocator
public class ViewModelLocator
{
//CONSTRUCTOR
static ViewModelLocator()
{
Kernel = new StandardKernel(new DataViewsModule());
}
//PRIVATE FIELDS
private static IKernel Kernel;
//PUBLIC PROPERTIES
public LiveDataViewModel LiveDataViewModel { get { return Kernel.Get<LiveDataViewModel>(); } }
/// <summary>
/// Cleans up all the resources.
/// </summary>
public static void Cleanup()
{
}
}
NinjectModule
class DataViewsModule : NinjectModule
{
public override void Load()
{
//View Models
Bind<DataViewsViewModel>().ToSelf().InSingletonScope();
Bind<LiveDataViewModel>().ToSelf().InTransientScope();
}
}
Constructor of View:
public LiveDataView()
{
InitializeComponent();
Unloaded += (s, e) => ViewModelLocator.Cleanup();
}
So here is an unloaded event of the view that calls the ViewModelLocator Cleanup method. How do I go about cleaning up this transient viewmodel?
When an object is bound in TransientScope, it means that it is only activated by Ninject when it is needed, but Ninject does not track that object anymore, so it is on your side to do the cleanup.
I would suggest to create some custom scope and make your viewmodel
IDisposable. Ninject will callDispose()method on that object at the and of the scope (not working for the transient scope because it is actually no scope at all). And it is good practice to make objects that hold some resources implementIDisposableso they will cleanup after themselves when the work is done.Also look at this interesting Ninject extension: https://github.com/ninject/ninject.extensions.namedscope/wiki . It provides some additional scopes implementations. I suggest you could try
InParentScope().