依赖注入和服务定位器模式有什么区别? [英] What's the difference between the Dependency Injection and Service Locator patterns?

查看:115
本文介绍了依赖注入和服务定位器模式有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种模式似乎都是控制反转原理的实现。也就是说,一个对象不应该知道如何构造它的依赖关系。



依赖注入(DI)似乎使用构造函数或setter来注入它的依赖关系。



使用构造函数注入的示例:

  // Foo需要一个IBar 
public class Foo
{
private IBar bar;

public Foo(IBar bar)
{
this.bar = bar;
}

// ...
}

服务定位器似乎使用一个容器,它连接了它的依赖项,并给出了它的条形码。



使用服务定位器的示例

  // Foo需要一个IBar 
public class Foo
{
private IBar bar;

public Foo()
{
this.bar = Container.Get< IBar>();
}

//
}



<因为我们的依赖关系只是对象本身,这些依赖关系具有依赖关系,它们具有更多的依赖关系等等。因此,控制容器的反转(或DI容器)诞生了。例如:Castle Windsor,Ninject,Structure Map,Spring等)



但是IOC / DI容器正好像服务定位器那样正好。称它是一个DI容器一个坏名字? IOC / DI容器是服务定位器的另一种类型吗?实际上,我们使用DI容器的情况主要是因为我们有很多依赖关系?

解决方案

差异可能看起来很轻微,但是即使使用ServiceLocator,该类仍然负责创建它的依赖关系。它只是使用服务定位器来做到这一点。使用DI,该类被赋予它的依赖性。它既不知道,也不关心他们来自哪里。一个重要的结果是,DI示例更容易进行单元测试 - 因为您可以传递其依赖对象的模拟实现。你可以组合这两个 - 并注入服务定位器(或工厂),如果你想要的。


Both patterns seem like an implementation of the principle of inversion of control. That is, that an object should not know how to construct its dependencies.

Dependency Injection (DI) seems to use a constructor or setter to "inject" it's dependencies.

Example of using Constructor Injection:

//Foo Needs an IBar
public class Foo
{
  private IBar bar;

  public Foo(IBar bar)
  {
    this.bar = bar;
  }

  //...
}

Service Locator seems to use a "container", which wires up its dependencies and gives foo it's bar.

Example of using a Service Locator:

//Foo Needs an IBar
public class Foo
{
  private IBar bar;

  public Foo()
  {
    this.bar = Container.Get<IBar>();
  }

  //...
}

Because our dependencies are just objects themselves, these dependencies have dependencies, which have even more dependencies, and so on and so forth. Thus, the Inversion of Control Container (or DI Container) was born. Examples: Castle Windsor, Ninject, Structure Map, Spring, etc.)

But a IOC/DI Container looks exactly like a Service Locator. Is calling it a DI Container a bad name? Is an IOC/DI Container just another type of Service Locator? Is the nuance in the fact that we use DI Containers mostly when we have many Dependencies?

解决方案

The difference may seem slight, but even with the ServiceLocator, the class is still responsible for creating its dependencies. It just uses the service locator to do it. With DI, the class is given it's dependencies. It neither knows, nor cares where they come from. One important result of this is that the DI example is much easier to unit test -- because you can pass it mock implementations of its dependent objects. You could combine the two -- and inject the service locator (or a factory), if you wanted.

这篇关于依赖注入和服务定位器模式有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆