One of common problems in MVVM is to have Service Locator .Here I created simple implementation on service locator pattern. First we will create interface IServiceLocator :
References :
public interface IServiceLocator { T GetInstance<T>() where T : IViewModel, new(); }
And also we have a Service locator class :
public class ServiceLocator : IServiceLocator
{
private IDictionary<object, object> instances;
private static IServiceLocator locator = new ServiceLocator();
private ServiceLocator()
{
instances = new Dictionary<object, object>();
}
public static IServiceLocator Current { get { return locator; } }
public T GetInstance<T>() where T : IViewModel,new()
{
try
{
return (T)instances[typeof(T)];
}
catch (KeyNotFoundException)
{
this.instances.Add(typeof(T), new T());
return (T)instances[typeof(T)];
}
}
public void RemoveInstance<T>() where T : IViewModel, new()
{
try
{
this.instances.Remove(typeof(T));
}
catch (KeyNotFoundException)
{
}
}
}
We have to use service locator to initialize the view model instance like this :
public partial class MyView : UserControl { public MyView() { InitializeComponent(); this.DataContext = ServiceLocator.Current.GetInstance<MyViewModel>(); } }
I hope this code helps and waiting for any comments (it is my first Silverlight experience).
References :