You can just unregister an instance of the class than remove the entire class if you want.
Snippet from SimpleIoc.cs
:
//
// Summary:
// Removes the instance corresponding to the given key from the cache. The class
// itself remains registered and can be used to create other instances.
//
// Parameters:
// key:
// The key corresponding to the instance that must be removed.
//
// Type parameters:
// TClass:
// The type of the instance to be removed.
public void Unregister<TClass>(string key) where TClass : class;
Do keep in mind to get a new instance of the class on every resolve from SimpleIoC
we need to specify a unique key to it in GetInstance()
so in ViewModelLocator.cs
keep a reference to the currentKey
used and un-register it on the next attempt, something like:
private string _currentScanVMKey;
public ScanViewModel Scan
{
get {
if (!string.IsNullOrEmpty(_currentScanVMKey))
SimpleIoc.Default.Unregister(_currentScanVMKey);
_currentScanVMKey = Guid.NewGuid().ToString();
return ServiceLocator.Current.GetInstance<ScanViewModel>(_currentScanVMKey);
}
}
This way each time the VMLocator is queried for Scan
a new VM is returned after unregistering the current VM. This approach would comply with the guidelines suggested by "Laurent Bugnion" Here and I'd take it he knows his own libraries pretty well and you're not going to go wrong doing it that way.
I remember MVVM Light's author state somewhere SimpleIoC
was intended to get dev's familiar with IOC principles and let them explore it for themselves. It's great for simple project's, If you do want more and more control over your VM injections then I'd suggest looking at things like Unity in which your current situation would have been resolved pretty easily since you could just go
// _container is a UnityContainer
_container.RegisterType<ScanViewModel>(); // Defaults to new instance each time when resolved
_container.RegisterInstance<ScanViewModel>(); // Defaults to a singleton approach
You also get LifeTimeManagers and sorts that give even greater control. Yes Unity is an overhead compared to SimpleIoC
, but it's what the technology can provide when needed than having to write code yourself.