如何使用MVVMLight SimpleIoc? [英] how to use MVVMLight SimpleIoc?
问题描述
我在我的改造软件,有凌乱的 Messenger.Default(...)
位。
I'm revamping my software which has messy Messenger.Default(...)
bits.
有没有小抄知道MVVMLight SimpleIoc使用(而不是一般的IoC说明)?
Is there any cheat sheet to know MVVMLight SimpleIoc usage (not general IoC description)?
推荐答案
SimpleIoc婴儿床表:
SimpleIoc crib sheet:
1)注册您的所有接口和对象在ViewModelLocator
1) You register all your interfaces and objects in the 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)每个对象都是单身默认。要解决的对象,因此,这不是你需要一个独特的价值传递给的GetInstance调用单:
2) 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<MainViewModel>(Guid.NewGuid().ToString());
3)要防止接口注册类:
3) To register a class against an interface:
SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
4)要注册一个对接口的具体对象:
4) To register a concrete object against an interface:
SimpleIoc.Default.Register<IDataService>(myObject);
5)要注册一个具体类型:
5) To register a concrete type:
SimpleIoc.Default.Register<MainViewModel>();
6)从接口解析的对象:
6) To resolve an object from an interface:
SimpleIoc.Default.GetInstance<IDataService>();
7)要直接解决一个对象(不积聚和依赖分辨率):
7) To resolve an object directly (does buildup and dependency resolution):
SimpleIoc.Default.GetInstance<MainViewModel>();
8)MVVM使得在做设计时的数据很容易:
8) MVVM makes doing design-time data really easy:
if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
}
else
{
SimpleIoc.Default.Register<IDataService, DataService>();
}
如果您在设计时模式是它会自动注册您的设计时服务,使得它很容易在VS设计师的工作时,在你的ViewModels和视图中的数据。
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.
希望这有助于。
这篇关于如何使用MVVMLight SimpleIoc?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!