【问题标题】:Is there a difference between SimpleIoc.Default.GetInstance and ServiceLocator.Current.GetInstanceSimpleIoc.Default.GetInstance 和 ServiceLocator.Current.GetInstance 之间有区别吗
【发布时间】:2012-12-26 18:23:28
【问题描述】:

我正在使用适用于 Windows 8 的 MVVM Light 第 4 版;它包括 SimpleIOC。在各种示例中,我有时会看到基于 SimpleIoc 请求对象的代码......有时它基于 ServiceLocator......

示例包括:

userToken = SimpleIoc.Default.GetInstance();

mainVM = ServiceLocator.Current.GetInstance();

使用 SimpleIoc.Default.GetInstance 和 ServiceLocator.Current.GetInstance 有什么区别?

如果没有区别,ServiceLocator 是否只是让我可以选择改变我想使用哪个 IOC 库的想法?如果我对 SimpleIoc 感到满意,ServiceLocator 是否只是提供了一个无关紧要的额外抽象层?或者,ServiceLocator 是否执行了其他一些对我们 IOC 新手来说并不明显的有用魔法?

感谢您的洞察力!

【问题讨论】:

  • 反弹...有人有真实的答案吗?

标签: inversion-of-control mvvm-light


【解决方案1】:

在您的 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,则不必更改您的代码。

【讨论】:

  • 你的回答只是陈述显而易见的,我的朋友。您所说的内容已隐含在问题中。
【解决方案2】:

根据 MSDN 上 Bugnion 先生的 article(在“注册类的各种方法”一节中),我假设 IoC 提供程序的可互换性是使用 ServiceLocator 的唯一原因。

正如@FasterSolutions 所说,SimpleIoc 实现了 IServiceLocator,所以我怀疑与您关于抽象层的说法相反的是正确的。我认为您应该使用 ServiceLocator,但这没有经验证据;也许有人可以证明我错了(?)

【讨论】:

    猜你喜欢
    • 2012-02-16
    • 2020-01-11
    • 2016-12-02
    • 2021-10-09
    • 2010-09-27
    • 2014-08-30
    • 2014-09-25
    • 2017-12-23
    • 2014-12-04
    相关资源
    最近更新 更多