zoukankan      html  css  js  c++  java
  • Why does one use dependency injection?

    Why does one use dependency injection?

    回答1

    I think a lot of times people get confused about the difference between dependency injection and a dependency injection framework (or a container as it is often called).

    Dependency injection is a very simple concept. Instead of this code:

    public class A {
      private B b;
    
      public A() {
        this.b = new B(); // A *depends on* B
      }
    
      public void DoSomeStuff() {
        // Do something with B here
      }
    }
    
    public static void Main(string[] args) {
      A a = new A();
      a.DoSomeStuff();
    }

    you write code like this:

    public class A {
      private B b;
    
      public A(B b) { // A now takes its dependencies as arguments
        this.b = b; // look ma, no "new"!
      }
    
      public void DoSomeStuff() {
        // Do something with B here
      }
    }
    
    public static void Main(string[] args) {
      B b = new B(); // B is constructed here instead
      A a = new A(b);
      a.DoSomeStuff();
    }

    And that's it. Seriously. This gives you a ton of advantages. Two important ones are the ability to control functionality from a central place (the Main() function) instead of spreading it throughout your program, and the ability to more easily test each class in isolation (because you can pass mocks or other faked objects into its constructor instead of a real value).

    The drawback, of course, is that you now have one mega-function that knows about all the classes used by your program. That's what DI frameworks can help with. But if you're having trouble understanding why this approach is valuable, I'd recommend starting with manual dependency injection first, so you can better appreciate what the various frameworks out there can do for you.

    Dependency Injection Demystified

    这个回答是简化了概念的理解,并且作者反对另外一个名人将概念复杂化

    Inversion of Control Containers and the Dependency Injection Pattern. Martin Fowler is my favorite author. Usually he's clear and concise. Here he succeeds in making dependency injection sound terribly complicated. Still, this article has a thorough discussion of the various ways dependency injection can be tweaked.

  • 相关阅读:
    算法学习——贪心篇
    Centos7下搭建LAMP环境,安装wordpress(不会生产博客,只是一名博客搬运工)(菜鸟)
    小白创建网站的曲折之路
    7.2.5 多层嵌套的if语句
    7.2.4 else与if配对
    7.2.3
    7.4 electirc.c -- 计算电费
    oracle数据库命令行查看存储过程
    Linux下如何查看进程准确启动时间
    7.2 if else 语句
  • 原文地址:https://www.cnblogs.com/chucklu/p/12583904.html
Copyright © 2011-2022 走看看