在您的 ViewModelLocator 类中,您可能有以下代码行:
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc 实现了IServiceLocator 接口,这意味着ServiceLocator 在调用时会将其用作DI 源。
编辑:
好的,人们想要“全脂且不放奶油”的答案。我们开始吧!
ServiceLocator 基本上是一个外壳。服务定位器的代码是:
public static class ServiceLocator
{
private static ServiceLocatorProvider currentProvider;
public static IServiceLocator Current
{
get
{
return ServiceLocator.currentProvider();
}
}
public static void SetLocatorProvider(ServiceLocatorProvider newProvider)
{
ServiceLocator.currentProvider = newProvider;
}
}
是的,就是这样。
ServiceLocatorProvider 是什么?它是一个委托,它返回一个实现IServiceLocator 的对象。
SimpleIoc 实现IServiceLocator。所以当我们这样做时:
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
我们将SimpleIoc 对象放入ServiceLocator。您现在可以使用其中任何一个,因为无论您调用 ServiceLocator.Current 还是 SimpleIoc.Default,您都返回了相同的对象实例。
那么,有什么区别
userToken = SimpleIoc.Default.GetInstance();
mainVM = ServiceLocator.Current.GetInstance();
?
不。没有任何。两者都是暴露一个静态属性的单例,该属性是IServiceLocator 的实现。如上所述,无论您调用哪个对象,您都将返回实现 IServiceLocator 的相同对象实例。
您可能想要使用ServiceLocator.Current.GetInstance() 而不是SimpleIoc.Default.GetInstance() 的唯一原因是,在将来的某个时候,您可能会更改 DI 容器,如果您使用 ServiceLocator,则不必更改您的代码。