Sometimes there is a requirement to temporarily store an object that can be later retrieved. My particular problem at the time was that I wanted to share a View Model with a second view, but alas neither view knows about one another.
My first thought was to store the view model object temporarily in a Unity Container. That way I could easily retrieve the object at a later time. This solution was not satisfactory however because this was only suppose to be a temporary storage solution and Unity does not support any unregister operation. Not having the ability to remove (unregister) the object was not an option.
My solution was to create a Temporary Storage Service. The service I am demonstrating here allows for the Deposit and the Withdrawal of data (objects). Some people may want to store the data for a little bit longer than straight in and straight out. This solution could easily be modified to suit.
My Temporary Storage Service looks like this.
public class TemporaryStorageService : ITemporaryStorageService
{
public void Deposit<T>(Object o, string key)
{
System.Windows.Application.Current.Properties[key] = o;
}
public T Withdraw<T>(string key)
{ T o = (T)System.Windows.Application.Current.Properties[key];
System.Windows.Application.Current.Properties.Remove(key);
return o;
}
}
The Interface
publicinterface ITemporaryStorageService
{
void Deposit<T>(Object o, string key);
T Withdraw<T>(string key);
}
Register the service with Unity
// Temporary Storage Service
ITemporaryStorageService temporaryStorageService = new TemporaryStorageService();
unityContainer.RegisterInstance<ITemporaryStorageService>(temporaryStorageService);
Now I can call my Service whenever I need to store any Objects temporarily. As I said above my immediate need was to store a view model temporarily. So this is what I did.
My first view creates a new view model and immediately puts it in temporary storage
public class SomeWindow : Window
{
ITemporaryStorageService _temporaryStorageService;
public SomeWindow(ITemporaryStorageService temporaryStorageService)
{
this._temporaryStorageService = temporaryStorageService;
InitializeComponent();
}
[Dependency]
public SharedViewModel VM
{
set
{
this.DataContext = value;
// We will store the view model in the Application Properites
this._temporaryStorageService.Deposit<SharedViewModel>(value, "SharedViewModel");
}
}
}
Then when I initialise my second view I call upon the stored viewmodel.
[Dependency]
public CashBook.MVVM.Services.ITemporaryStorageService TemporaryStorageService
{
set
{
this.DataContext = value.Withdraw<SharedViewModel>("SharedViewModel");
}
}
Works like a charm!