What does dependency injection mean?

This question already has an answer here:

  • What is dependency injection? 31 answers

  • Dependency Injection allows the developer to put a class reference into a project a will without having to create it as an object.

    In the case of spring, where I have most knowledge of DI, I would like the classpath in a config.xml file and I can pass this class reference to any class were I need it to be called. The class being injected is like a singleton as only that one reference is being passed without declaring it as a singleton. It is usually a service class that is injected.

    Dependency injection allows a client the flexibility of being configurable. Only the client's behaviour is fixed. This can save time swapping out what is to be injected in an xml file without the need to recompile the project.

    This is why I say it is more like a singleton using only one instance

        public class Foo {    
            // Constructor
            public Foo() {
                // Specify a specific implementation in the constructor instead of using dependency injection
                Service service1 = new ServiceExample();
            }
    
            private void RandomMethod() {
                Service service2 = new ServiceExample();
            }
        }
    

    Here the one service is used twice because two instances are created. I have seen projects where class files have become so big where a service class was created three times through out the one class in different methods.

        public class Foo {
            // Internal reference to the service
            private Service service1;
    
            // Constructor
            public Foo(Service service1) {
                this.service1 = service1;
            }
        } 
    

    The same issuse can be created in the second example but by having all dependencies in the constructor, it makes it a little more obvious to the developer looking at the code what is being used and that the service has already been created from the start.


    Code Injection may have various meanings depending on context.

    For example, in a security context it can mean malicious code being injected into your application (eg. sql-injection).

    In other contexts (eg aspect-oriented programming) it might mean a way to patch a method with additional code for an aspect.

    Dependency Injection is something different and means a way for one part of code (eg a class) to have access to dependencies (other parts of code, eg other classes, it depends upon) in a modular way without them being hardcoded (so they can change or be overriden freely, or even be loaded at another time, as needed)

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

    上一篇: 为什么在MVC应用程序中使用IoC?

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