参考:https://stackoverflow.com/questions/130794/what-is-dependency-injection

原文:https://www.jamesshore.com/Blog/Dependency-Injection-Demystified.html

The Really Short Version

Dependency injection means giving an object its instance variables. Really. That's it.

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

Let's try simple example with Car and Engine classes, any car need an engine to go anywhere, at least for now. So below how code will look without dependency injection.

public class Car
{
public Car()
{
GasEngine engine = new GasEngine();
engine.Start();
}
} public class GasEngine
{
public void Start()
{
Console.WriteLine("I use gas as my fuel!");
}
}

And to instantiate the Car class we will use next code:

Car car = new Car();

The issue with this code that we tightly coupled to GasEngine and if we decide to change it to ElectricityEngine then we will need to rewrite Car class. And the bigger the application the more issues and headache we will have to add and use new type of engine.

In other words with this approach is that our high level Car class is dependent on the lower level GasEngine class which violate Dependency Inversion Principle(DIP) from SOLID. DIP suggests that we should depend on abstractions, not concrete classes. So to satisfy this we introduce IEngine interface and rewrite code like below:

    public interface IEngine
{
void Start();
} public class GasEngine : IEngine
{
public void Start()
{
Console.WriteLine("I use gas as my fuel!");
}
} public class ElectricityEngine : IEngine
{
public void Start()
{
Console.WriteLine("I am electrocar");
}
} public class Car
{
private readonly IEngine _engine;
public Car(IEngine engine)
{
_engine = engine;
} public void Run()
{
_engine.Start();
}
}

Now our Car class is dependent on only the IEngine interface, not a specific implementation of engine. Now, the only trick is how do we create an instance of the Car and give it an actual concrete Engine class like GasEngine or ElectricityEngine. That's where Dependency Injection comes in.

   Car gasCar = new Car(new GasEngine());
gasCar.Run();
Car electroCar = new Car(new ElectricityEngine());
electroCar.Run();

Here we basically inject(pass) our dependency(Engine instance) to Car constructor. So now our classes have loose coupling between objects and their dependencies, and we can easily add new types of engines without changing the Car class.

The main benefit of the Dependency Injection that classes are more loosely coupled, because they do not have hard-coded dependencies. This follows the Dependency Inversion Principle, which was mentioned above. Instead of referencing specific implementations, classes request abstractions (usually interfaces) which are provided to them when the class is constructed.

So in the end Dependency injection is just a technique for achieving loose coupling between objects and their dependencies. Rather than directly instantiating dependencies that class needs in order to perform its actions, dependencies are provided to the class (most often) via constructor injection.

Also when we have many dependencies it is very good practice to use Inversion of Control(IoC) containers which we can tell which interfaces should be mapped to which concrete implementations for all our dependencies and we can have it resolve those dependencies for us when it constructs our object. For example, we could specify in the mapping for the IoC container that the IEnginedependency should be mapped to the GasEngine class and when we ask the IoC container for an instance of our Car class, it will automatically construct our Car class with a GasEngine dependency passed in.

UPDATE: Watched course about EF Core from Julie Lerman recently and also liked her short definition about DI.

Dependency injection is a pattern to allow your application to inject objects on the fly to classes that need them, without forcing those classes to be responsible for those objects. It allows your code to be more loosely coupled, and Entity Framework Core plugs in to this same system of services.

最新文章

  1. linux python升级和ipython的安装
  2. nginx基于IP的虚拟主机
  3. 在linux中的info手册的用法
  4. 101 个 MySQL 的调节和优化的提示(根据实际情况调整,有些已经不适用)
  5. Android内存Activity泄露:Threads
  6. (WCF) WCF and Service Debug
  7. Google Map和桌面组件 Android开发教程
  8. css所有选择器的详解
  9. 使用 Docker 容器应该避免的 10 个事情
  10. hdu3534,个人认为很经典的树形dp
  11. txt 开关 csv 可通用 工具
  12. 理解free命令
  13. C++ Primer 有感(异常处理)(二)
  14. 【DFS】困难的串
  15. [Swift]LeetCode1000. 合并石头的最低成本 | Minimum Cost to Merge Stones
  16. 【高精度】高精度分数[c++]
  17. 带你入门 Docker
  18. nginx如何实现高并发
  19. 1.在html中引入js文件和Jquery框架
  20. Linux/Mac安装oh-my-zsh后不执行~/.bash_profile、~/.bashrc解决办法

热门文章

  1. spring-boot 速成(3) actuator
  2. ajax jquery 异步表单验证
  3. 使用Oracle DBLink进行数据库之间对象的訪问操作
  4. delphi代码实现窗口最小化,最大化,关闭消息发送
  5. 认识TWICImage类
  6. 一个最简单的Delphi2010的PNG异形窗口方法
  7. C#编程(十七)----------Object类
  8. 犯罪现场调查第一季/全集CSI迅雷下载
  9. 详解Java多线程编程中LockSupport类的线程阻塞用法
  10. 《Python自然语言处理》