how to use MVVMLight SimpleIoc?
C#WpfInversion of-ControlMvvm LightWindows Store-AppsC# Problem Overview
I'm revamping my software which has messy Messenger.Default(...)
bits.
Is there any cheat sheet to know MVVMLight SimpleIoc usage (not general IoC description)?
C# Solutions
Solution 1 - C#
SimpleIoc crib sheet:
-
You register all your interfaces and objects in the ViewModelLocator
class ViewModelLocator { static ViewModelLocator() {
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (ViewModelBase.IsInDesignModeStatic) {
SimpleIoc.Default.Register();
}
else
{
SimpleIoc.Default.Register();
}
SimpleIoc.Default.Register();
SimpleIoc.Default.Register(); } public MainViewModel Main { get { return ServiceLocator.Current.GetInstance<MainViewModel>(); } }
}
-
Every object is a singleton by default. To resolve an object so that it's not a singleton you need to pass a unique value to the GetInstance call:
SimpleIoc.Default.GetInstance
(Guid.NewGuid().ToString()); -
To register a class against an interface:
SimpleIoc.Default.Register
(); -
To register a concrete object against an interface:
SimpleIoc.Default.Register
(myObject); -
To register a concrete type:
SimpleIoc.Default.Register
(); -
To resolve an object from an interface:
SimpleIoc.Default.GetInstance
(); -
To resolve an object directly (does buildup and dependency resolution):
SimpleIoc.Default.GetInstance
(); -
MVVM makes doing design-time data really easy:
if (ViewModelBase.IsInDesignModeStatic) {
SimpleIoc.Default.Register();
}
else
{
SimpleIoc.Default.Register();
}
If you're in design-time mode it will automatically register your design-time services, making it really easy to have data in your viewmodels and views when working in the VS designer.
Hope this helps.