原文:https://www.dotnettricks.com/learn/dependencyinjection/understanding-inversion-of-control-dependency-injection-and-service-locator

-----------------------------------------------------------------------------------------

Understanding Inversion of Control, Dependency Injection and Service Locator

Print

   Author : Shailendra Chauhan
 Posted On : 10 Apr 2013
 Total Views : 133,973   
 Updated On : 26 Sep 2016
 

So many developers are confused about the the term Dependency Injection (DI). The confusion is about terminology, purpose, and mechanics. Should it be called Dependency Injection, Inversion of Control, or Service Locator? Over the Internet, there are a lot of articles, presentations and discussion but, unfortunately, many of them use conflicting terminology. In this article I would like to explain, all these three OOPS concepts.

Dependency Inversion Principle (DIP)

The Dependency Inversion Principle states that:

  1. High level modules should not depend upon low level modules. Both should depend upon abstractions.

  2. Abstractions should not depend upon details. Details should depend upon abstractions.

The Dependency Inversion principle (DIP) helps us to develop loosely couple code by ensuring that high-level modules depend on abstractions rather than concrete implementations of lower-level modules. The Inversion of Control pattern is an implementation of this principle

Inversion of Control (IoC)

The term Inversion of Control (IoC) refers to a programming style where a framework or runtime, controls the program flow. Inversion of control means we are changing the control from normal way. It works on Dependency Inversion Principle. The most software developed on the .NET Framework uses IoC.

For example

  1. When you write an ASP.NET application, you lie into the ASP.NET page life cycle, but you aren’t in control while ASP.NET is.

  2. When you write a WCF service, you implement interfaces decorated with attributes. You may be writing the service code, but ultimately, you aren’t in control while WCF is.

More over IoC is a generic term and it is not limited to DI. Actually, DI and Service Locator patterns are specialized versions of the IoC pattern or you can say DI and Service Locator are the ways of implementing IoC.

For example, Suppose your Client class needs to use a Service class component, then the best you can do is to make your Client class aware of an IService interface rather than a Service class. In this way, you can change the implementation of the Service class at any time (and for how many times you want) without breaking the host code.

IoC and DIP

DIP says High level module should not depend on low level module and both should depend on abstraction. IoC is a way that provide abstraction. A way to change the control. IoC gives some ways to implement DIP. If you want to make independent higher level module from the lower level module then you have to invert the control so that low level module not controlling interface and creation of the object. Finally IoC gives some way to invert the control.

IoC and DI

The terms Dependency Injection (DI) & Inversion of Control (IoC) are generally used interchangeably to describe the same design pattern. The pattern was originally called IoC, but Martin Fowler proposed the shift to DI because all frameworks invert control in some way and he wanted to be more specific about which aspect of control was being inverted.

Dependency Injection (DI)

DI is a software design pattern that allow us to develop loosely coupled code. DI is a great way to reduce tight coupling between software components. DI also enables us to better manage future changes and other complexity in our software. The purpose of DI is to make code maintainable.

The Dependency Injection pattern uses a builder object to initialize objects and provide the required dependencies to the object means it allows you to "inject" a dependency from outside the class.

Service Locator (SL)

Service Locator is a software design pattern that also allow us to develop loosely coupled code. It implements the DIP principle and easier to use with an existing codebase as it makes the overall design looser without forcing changes to the public interface.

The Service Locator pattern introduces a locator object that objects is used to resolve dependencies means it allows you to "resolve" a dependency within a class.

Dependency Injection and Service Locator with Example

Let's consider the simple dependency between two classes as shown in the fig and it is a simple approach, that you know.

Now have a look at the folllowing code:

  1. public class Service
  2. {
  3. public void Serve()
  4. {
  5. Console.WriteLine("Service Called");
  6. //To Do: Some Stuff
  7. }
  8. }
  9. public class Client
  10. {
  11. private Service _service;
  12. public Client()
  13. {
  14. this._service = new Service();
  15. }
  16. public void Start()
  17. {
  18. Console.WriteLine("Service Started");
  19. this._service.Serve();
  20. //To Do: Some Stuff
  21. }
  22. }

Clearly, the Client class has a dependency on the Service class. If you want to make it loosely coupled, you have to use IoC to make the more flexible and reusable it.

To implement the IoC, you have the choice of two main patterns: Service Locator and Dependency Injection. The Service Locator allows you to "resolve" a dependency within a class and the Dependency Injection allows you to "inject" a dependency from outside the class.

Using Service Locator

The above code can be re-written as by using Service Locator as follows.

  1. public interface IService
  2. {
  3. void Serve();
  4. }
  5. public class Service : IService
  6. {
  7. public void Serve()
  8. {
  9. Console.WriteLine("Service Called");
  10. //To Do: Some Stuff
  11. }
  12. }
  13. public static class LocateService
  14. {
  15. public static IService _Service { get; set; }
  16. public static IService GetService()
  17. {
  18. if (_Service == null)
  19. _Service = new Service();
  20. return _Service;
  21. }
  22. }
  23. public class Client
  24. {
  25. private IService _service;
  26. public Client()
  27. {
  28. this._service = LocateService.GetService();
  29. }
  30. public void Start()
  31. {
  32. Console.WriteLine("Service Started");
  33. this._service.Serve();
  34. //To Do: Some Stuff
  35. }
  36. }

Sample ServiceLocator-Implementation:

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. var client = new Client();
  6. client.Start();
  7. Console.ReadKey();
  8. }
  9. }

The Inversion happens in the constructor, by locating the Service that implements the IService-Interface. The dependencies are assembled by a "Locator".

Using Dependency Injection

The above code can also be re-written as by using Dependency Injection as follows.

  1. public interface IService
  2. {
  3. void Serve();
  4. }
  5. public class Service : IService
  6. {
  7. public void Serve()
  8. {
  9. Console.WriteLine("Service Called");
  10. //To Do: Some Stuff
  11. }
  12. }
  13. public class Client
  14. {
  15. private IService _service;
  16. public Client(IService service)
  17. {
  18. this._service = service;
  19. }
  20. public void Start()
  21. {
  22. Console.WriteLine("Service Started");
  23. this._service.Serve();
  24. //To Do: Some Stuff
  25. }
  26. }

Sample Builder-Implementation:

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. client = new Client(new Service());
  6. client.Start();
  7. Console.ReadKey();
  8. }
  9. }

The Injection happens in the constructor, by passing the Service that implements the IService-Interface. The dependencies are assembled by a "Builder" and Builder responsibilities are as follows:

  1. knowing the types of each IService

  2. according to the request, feed the abstract IService to the Client

What's wrong with the above two approaches?

Above two approaches can be resemble to DI FACTORY. There are some issues with the above two approaches:

  1. It is hardcoded and can't be reused across applications, due to hardcoded factories. This makes the code stringent to particular implementations.

  2. It is Interface dependent since interfaces are used for decoupling the implementation and the object creation procedure.

  3. It's Instantiating instantiations are very much custom to a particular implementation.

  4. Everything is compile time since all the dependent types for the objects in the instantiation process (factory) have to be known at compile time.

What is the Solution ?

IoC containers is the solution to resolve above two approaches issues. Hence, when we compose applications without a DI CONTAINER, it is like a POOR MAN’S DI. Moreover, DI CONTAINER is a useful, but optional tool.

You can also improve above two approaches by doing some more work. You can also combine above two approaches to make code more independent

Dependency Injection VS Service Locator

  1. When you use a service locator, every class will have a dependency on your service locator. This is not the case with dependency injection. The dependency injector will typically be called only once at startup, to inject dependencies into the main class.

  2. The Service Locator pattern is easier to use in an existing codebase as it makes the overall design looser without forcing changes to the public interface. Code that is based on the Service Locator pattern is less readable than the equivalent code that is based on Dependency Injection.

References

http://www.objectmentor.com/resources/articles/dip.pdf

http://satoricode.net/2011/10/01/UnderstandingTheBenefitsOfADependencyInjectionContainerIOC.aspx

What do you think?

I hope you will enjoy the DIP, IoC, DI and SL patterns. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

【转】Understanding Inversion of Control, Dependency Injection and Service Locator Print的更多相关文章

  1. Inversion of Control Containers and the Dependency Injection pattern(转)

    In the Java community there's been a rush of lightweight containers that help to assemble components ...

  2. Inversion of Control Containers and the Dependency Injection pattern--Martin Fowler

    原文地址:https://martinfowler.com/articles/injection.html n the Java community there's been a rush of li ...

  3. [转载][翻译] IoC 容器和 Dependency Injection 模式

    原文地址:Inversion of Control Containers and the Dependency Injection pattern 中文翻译版本是网上的PDF文档,发布在这里仅为方便查 ...

  4. Dependency Injection

    Inversion of Control - Dependency Injection - Dependency Lookup loose coupling/maintainability/ late ...

  5. 控制反转Inversion of Control (IoC) 与 依赖注入Dependency Injection (DI)

    控制反转和依赖注入 控制反转和依赖注入是两个密不可分的方法用来分离你应用程序中的依赖性.控制反转Inversion of Control (IoC) 意味着一个对象不会新创建一个对象并依赖着它来完成工 ...

  6. Inversion of Control Containers and the Dependency Injection pattern

    https://martinfowler.com/articles/injection.html One of the entertaining things about the enterprise ...

  7. 控制反转(Inversion of Control,英文缩写为IoC),另外一个名字叫做依赖注入(Dependency Injection,简称DI)

    控制反转(Inversion of Control,英文缩写为IoC),另外一个名字叫做依赖注入(Dependency Injection,简称DI),是一个重要的面向对象编程的法则来削减计算机程序的 ...

  8. AngularJs学习笔记--Dependency Injection(DI,依赖注入)

    原版地址:http://code.angularjs.org/1.0.2/docs/guide/di 一.Dependency Injection(依赖注入) 依赖注入(DI)是一个软件设计模式,处理 ...

  9. 控制反转(Inversion of Control)之我的理解

    关于控制反转(Inversion of Control),在具体实现上也有许多其它的叫法,如依赖倒置(Dependency Inversion Principles, DIP).依赖注入(Depend ...

随机推荐

  1. busybox根文件系统使用记录

    1.DHCP功能配置 1.1.配置Linux内核使能DHCP相关选项: [*]Networking support --> Networking support Networking optio ...

  2. js常用数组去重

    // ES6 function unique (arr){ const seen = new Map() return arr.filter((a) => !seen.has(a) && ...

  3. 知问前端——对话框UI(二)

    dialog()方法的事件 除了属性设置外,dialog()方法也提供了大量的事件,这些事件可以给各种不同状态时的对话框提供回调函数,这些回调函数中的this值等于对话框内容的div对象,不是整个对话 ...

  4. 洛谷 P1343 地震逃生

    P1343地震逃生 题目描述 汶川地震发生时,四川**中学正在上课,一看地震发生,老师们立刻带领x名学生逃跑,整个学校可以抽象地看成一个有向图,图中有n个点,m条边.1号点为教室,n号点为安全地带,每 ...

  5. webdriver操作iframe标记的编辑器

    1.iFrame有ID 或者 name的情况//进入id="frame1"的frame中,定位id="div1"的div和id="input1&quo ...

  6. linux用户态定时器的使用---19【转】

    转自:http://www.cnblogs.com/zxouxuewei/p/5095288.html 原创博文,转载请标明出处--周学伟http://www.cnblogs.com/zxouxuew ...

  7. 【原创】Linux环境下的图形系统和AMD R600显卡编程(6)——AMD显卡GPU命令格式

    前面一篇blog里面描述了命令环缓冲区机制,在命令环机制下,驱动写入PM4(不知道为何会取这样一个名字)包格式的命令对显卡进行配置.这一篇blog将详细介绍命令包的格式. 当前定义了4中命令包,分别是 ...

  8. 6.安装和配置OpenStack图片服务组件

    安装和配置图片服务组件 这里是安装在控制器上 安装和配置图片服务组件 yum install –y openstack-glance python-glanceclient 编辑/etc/glance ...

  9. android的百度地图开发(一)

    1,注册百度开发者账号 2,申请key  ,注意开发版SH和发布版的SH  获取开发版SHA1: 输入命令:keytool -list -v -keystore debug.keystore,回车输入 ...

  10. 【QC】安装

    QC不支持win8 1. 开启win8自带的IIS服务. 在控制面板-程序-启用或关闭Windows功能-Internet Information Service