How to use MVVMLight SimpleIoc?

I am updating my software with messy bits of Messenger.Default(...) .

Is there a cheat sheet for reading MVVMLight SimpleIoc (not a general description of IoC)?

+47
c # inversion-of-control wpf windows-store-apps mvvm-light
Dec 10
source share
1 answer

SimpleIoc sleepers sheet:

1) You register all your interfaces and objects in ViewModelLocator

 class ViewModelLocator { static ViewModelLocator() { ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); if (ViewModelBase.IsInDesignModeStatic) { SimpleIoc.Default.Register<IDataService, Design.DesignDataService>(); } else { SimpleIoc.Default.Register<IDataService, DataService>(); } SimpleIoc.Default.Register<MainViewModel>(); SimpleIoc.Default.Register<SecondViewModel>(); } public MainViewModel Main { get { return ServiceLocator.Current.GetInstance<MainViewModel>(); } } } 

2) By default, each object is single. To enable the object so that it is not selected, you need to pass a unique value to the GetInstance call:

 SimpleIoc.Default.GetInstance<MainViewModel>(Guid.NewGuid().ToString()); 

3) To register a class by interface:

 SimpleIoc.Default.Register<IDataService, Design.DesignDataService>(); 

4) To register a specific object by interface:

 SimpleIoc.Default.Register<IDataService>(myObject); 

5) To register a specific type:

 SimpleIoc.Default.Register<MainViewModel>(); 

6) To resolve an object from the interface:

 SimpleIoc.Default.GetInstance<IDataService>(); 

7) To resolve the object directly (dependency creation and resolution is done):

 SimpleIoc.Default.GetInstance<MainViewModel>(); 

8) MVVM makes development-time data very simple:

 if (ViewModelBase.IsInDesignModeStatic) { SimpleIoc.Default.Register<IDataService, Design.DesignDataService>(); } else { SimpleIoc.Default.Register<IDataService, DataService>(); } 

If you are in development time mode, it automatically registers your development time services, which makes it very easy to store data in your models and views when working in the VS designer.

Hope this helps.

+108
Dec 10 '12 at 16:32
source share



All Articles