How to reset all instances in IOC Container

你离开我真会死。 提交于 2019-12-06 03:09:14

问题


I have made an C# WPF Application using the MVVM Light framework. My Application uses the ViewModelLocator class to locate the viewmodels during runtime. The ViewModelLocator makes usage of the SimpleIoc class which also comes with the MVVM Light framework.

Here is my scenario: The user logs in an can use my application. On logout, i want to dispose/reset/recreate all viewmodel instances to provide a clean environment to the next user.

I tried to implement the Cleanup() method in the ViewModelLocator class but it is not working. Not working means that the (second) user sees the data from the user who was logged in before.

first try:

public static void Cleanup()
{
   SimpleIoc.Default.Reset();
}

second try:

public static void Cleanup()
{
   SimpleIoc.Default.Unregister<LoginViewModel>();
   SimpleIoc.Default.Unregister<TaskViewModel>();

   SimpleIoc.Default.Register<LoginViewModel>();
   SimpleIoc.Default.Register<TaskViewModel>();
}

third try (not what i want but it is a workaround):

public static void Cleanup()
{
   // I implemented the ICleanup interface in my viewmodels
   // The cleanup method clears all my variables eg: myCollection.clear();
   SimpleIoc.Default.GetInstance<LoginViewModel>().Cleanup();
   SimpleIoc.Default.GetInstance<TaskViewModel>().Cleanup();
}

How do i reset all instances in my ViewModelLocator class? I'm willing to use a more advanced Ioc Container if necessary.


回答1:


With SimpleIoC

I'd add a public static property with a private string backend for a unique Key

something like

private static string _currentKey = System.Guid.NewGuid().ToString();
public static string CurrentKey {
  get {
    return _currentKey;
  }
  private set {
    _currentKey = value;
  }
}

and have the cleanup method to unregister VM's with current key and finally reset the current key(invoke on each app reset stage):

public static void Cleanup() {
  SimpleIoc.Default.Unregister<LoginViewModel>(CurrentKey);
  ...
  CurrentKey = System.Guid.NewGuid().ToString();
}

and when calling GetInstance(...) just pass in the static CurrentKey.

SimpleIoc.Default.GetInstance<LoginViewModel>(ViewModelLocator.CurrentKey);


来源:https://stackoverflow.com/questions/17043018/how-to-reset-all-instances-in-ioc-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!