参考: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.

What is dependency injection and when/why should or shouldn't it be used?的更多相关文章

  1. Ninject学习(一) - Dependency Injection By Hand

    大体上是把官网上的翻译下而已. http://www.ninject.90iogjkdcrorg/wiki.html Dependency Injection By Hand So what's Ni ...

  2. MVC Controller Dependency Injection for Beginners【翻译】

    在codeproject看到一篇文章,群里的一个朋友要帮忙我翻译一下顺便贴出来,这篇文章适合新手,也算是对MEF的一个简单用法的介绍. Introduction In a simple stateme ...

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

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

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

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

  5. Dependency Injection

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

  6. 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 ...

  7. Scala 深入浅出实战经典 第57讲:Scala中Dependency Injection实战详解

    王家林亲授<DT大数据梦工厂>大数据实战视频 Scala 深入浅出实战经典(1-87讲)完整视频.PPT.代码下载:百度云盘:http://pan.baidu.com/s/1c0noOt6 ...

  8. 【译】Dependency Injection with Autofac

    先说下为什么翻译这篇文章,既定的方向是架构,然后为了学习架构就去学习一些架构模式.设计思想. 突然有一天发现依赖注入这种技能.为了使得架构可测试.易维护.可扩展,需要架构设计为松耦合类型,简单的说也就 ...

  9. 依赖注入 | Dependency Injection

    原文链接: Angular Dependency Injection翻译人员: 铁锚翻译时间: 2014年02月10日说明: 译者认为,本文中所有名词性的"依赖" 都可以理解为 & ...

  10. 黄聪:Microsoft Enterprise Library 5.0 系列教程(八) Unity Dependency Injection and Interception

    原文:黄聪:Microsoft Enterprise Library 5.0 系列教程(八) Unity Dependency Injection and Interception 依赖注入容器Uni ...

随机推荐

  1. 外键的约束(Mysql、PostgreSQL)

    关于外键是什么,具体不再详述,可以自行百度. 讲一下关于外键的 On Delete和On Update的使用 最近在项目的表中看到这些,不懂顺便查了查: ONSTRAINT "c_clust ...

  2. 解决Windows x86网易云音乐不能将音乐下载到SD卡的BUG

    由于我个人最常用的电脑是Surface pro4 256G版本,装了不少生产力空间还挺吃紧的,音乐之类的必然都存单独的SD卡里.用UWP版本的网易云音乐倒是没问题,最近问题来了,UWP版本的网易云音乐 ...

  3. ICE::Handle 使用崩溃问题

    简单例子如下: #include "Ice/Ice.h" #include "IceUtil/IceUtil.h" #include "Printer ...

  4. logstash grok 分割匹配日志

    使用logstash的时候,为了更细致的切割日志,会写一些正则表达式. 使用方法 input { file { type => "billin" path => &qu ...

  5. 使用 IntraWeb (9) - JavaScript

    IW 依赖 js 构建(我数了数, 在当前版本它的资源文件默认携带了 26 个 js); 但 IW 尽可能地让用户少用或不用 js, 但如果你对 js 也不陌生, IW 提供了多种途径与方便. 我给它 ...

  6. Linux下以.rc结尾的文件含义

    运行命令 资源控制 运行控制 运行时配置 其实我更青睐于运行时配置,也就是运行时的变量等放置变量的. 参考: https://stackoverflow.com/questions/11030552/ ...

  7. Linux Delay Accounting

    https://andrestc.com/post/linux-delay-accounting/ Ever wondered how long is your program spending wh ...

  8. FTP服务器原理(转)

    本文转自https://www.cnblogs.com/Aiapple/p/5955736.html 感谢作者   21.1 FTP服务器原理   使用明码传输方式,且有相当多的安全危机历史.因此一般 ...

  9. C#高级编程小结

    小结 这几章主要介绍了如何使用新的dynamic类型,还讨论了编译器在遇到dynamic类型时会做什么.还讨论了DLP,可以把它包含在简单的应用程序中.并通过Pythin使用DLR,执行Python脚 ...

  10. 真爱如血第一季/全集True Blood迅雷下载

    第一季 True Blood Season 1 (2008)看点:该剧根据小说<南方吸血鬼>(Southern Vampire)改编,故事围绕路易斯安那州的吸血鬼和人类展开,当日本将人造血 ...