Explanation Dependency Injection

This question already has an answer here:

  • What is dependency injection? 31 answers

  • 1 When should I use dependency injection?

    You should use dependency injection when you want to have control over which dependencies you class/method will use at runtime. The best example of this is when you might want to replace a dependency that accesses a database with one that uses memory for unit testing purposes.

    2 Why should I use it?

    It makes your code more testable, more flexible and more extensible.

    3 What does in it easy words ? How is it working?

    It usually works by passing dependencies as parameters to a method or to a class's constructor.

    4 Is it like creating a factory for recycling your code/scripts?

    No. See 1.

    5 How does it interact and how do I call it when I use a front-controller ( For example )?

    Whatever creates the class or calls the method will need to satisfy that class/method's dependencies. This might be as simple as 'newing' up a object or getting a IoC framework to wire it all up for you.


    Basically by using dependency injection, you will get rid of static dependencies. Eg framework or w/e will handle dependencies for you. Its desing pattern used to prevent loose coupling and similar issues.

    For more detailed info try wiki.

    Regards Inty

    链接地址: http://www.djcxy.com/p/14410.html

    上一篇: 依赖注入是什么意思?

    下一篇: 解释依赖注入