Thursday, February 16, 2012

MVVM ViewModel Service Locator Sample

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 :
    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 :
  1. Stefano Ricciardi Blog

Tuesday, July 26, 2011

Hanselminutes Podcast 272 - Basics of Web Security with Barry Dorrans - Scott Hanselman

This podcast touches a part of my character click here

The top 9+7 things every programmer or architect should know - Java Code Geeks

I really like this article find it here

Wednesday, July 6, 2011

Developing Android applications using .Net

For long time i believed that i can not develop android applications using .Net but recently i found tutorial link on twitter which surprised me .
click here to open the tutorial .

Thursday, February 17, 2011

From Egypt With Love