如果需要,您可以只注销该类的一个实例,而不是删除整个类。
来自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;
请记住,每次从 SimpleIoC 解析时都要获取该类的新实例,我们需要在 GetInstance() 中为其指定唯一键
所以在ViewModelLocator.cs 中保留对currentKey 的引用并在下次尝试时取消注册,例如:
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);
}
}
这样,每次在 VMLocator 中查询 Scan 时,在取消注册当前 VM 后都会返回一个新 VM。这种方法符合“Laurent Bugnion”Here 建议的指导方针,我认为他非常了解自己的库,这样做不会出错。
我记得 MVVM Light 的作者状态 SimpleIoC 旨在让开发人员熟悉 IOC 原则并让他们自己探索。这对于简单的项目来说非常有用,如果您确实希望对 VM 注入进行越来越多的控制,那么我建议您查看 Unity 之类的东西,您目前的情况很容易解决,因为您可以去
// _container is a UnityContainer
_container.RegisterType<ScanViewModel>(); // Defaults to new instance each time when resolved
_container.RegisterInstance<ScanViewModel>(); // Defaults to a singleton approach
您还可以获得 LifeTimeManagers 和排序功能,可以提供更大的控制权。是的,与 SimpleIoC 相比,Unity 是一种开销,但这是该技术在需要时可以提供的,而不是自己编写代码。