Dependency injection

I've just seen the question "how to explain dependency injection to a 5-year-old" on stackoverflow.com,and there is one of the answers below.

If you have a class Employee and this employee has an Address you can have the Employee class defined as follows:

class Employee {
    private Address address;

    // constructor 
    public Employee( Address newAddress ) {
        this.address = newAddress;
    }

    public Address getAddress() {
    return this.address;
    }
    public void setAddress( Address newAddress ) {
        this.address = newAddress;
    }
}

Everything looks fine so far.

This code shows a HAS-A relationship between the employee and his address, that's fine.

Now, this HAS-A relationship created a dependency between them. The problem comes within the constructor.

Each time you want to create an Employee instance you need an Address instance:

 Address someAddress = ....
 Employee oscar = new Employee( someAddress ); 

Working this way becomes problematic especially when you want to perform unit testing.

The main problem comes when you need to test one particular object, you need to create an instance of other object, and most likely you need to create an instance of yet other object to do that. The chain may become unmanageable.

To avoid this, you could change the constructor like this:

  public Employee(){
  }

Using a no args constructor.

Then you can set the address when ever you want:

 Address someAddress = ....
 Employee oscar = new Employee();
 oscar.setAddress( someAddress ); 

Now, this may be a drag, if you have several attributes or if the objects are hard to create.

Yet, think about this, let's say, you add the Department attribute:

  class Employee {
      private Address address;
      private Department department;

  ....

If you have 300 employees, and all of them need to have the same department, and plus that same department has to be shared between some other objects ( like the company list of departments, or the roles each department have etc ) then you'll have a hard time with the visibility of the Departmentobject and to share it through all the network of objects.

What the Dependency Injection is all about it to help you to, well, "inject" these dependencies in your code. Most of the frameworks allow you to do this by specifying in an external file, what object is to be injected.

Assume a properties file for a fictitious dependency injector:

  #mock employee
  employee.address = MockAddress.class
  employee.department = MockDepartment.class

  #production setup 
  employee.address = RealAddress.class
  employee.department = RealDepartment.class

You'll define what to inject for a given scenario.

What the Dependency Injector framework will do is to set the correct objects for you, so you don't have to code setAddress or setDepartment. This would be done either by reflection or by code generation or other techniques.

So, the next time you need to test the Employee class you may inject mock Address and Departments objects without having to code all the set/get for all your test. Even better, you can injectreal Address and Department objects in production code, and still have the confidence your code works as tested.

That's pretty much about it.

Still I don't think this explanation is suitable for a 5 yr old as you requested.

I hope you still find it useful.

转载于:https://www.cnblogs.com/codegod520/p/4745660.html

Summary Dependency Injection Principles, Practices, and Patterns teaches you to use DI to reduce hard-coded dependencies between application components. You'll start by learning what DI is and what types of applications will benefit from it. Then, you'll work through concrete scenarios using C# and the .NET framework to implement DI in your own projects. As you dive into the thoroughly-explained examples, you'll develop a foundation you can apply to any of the many DI libraries for .NET and .NET Core. Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications. About the Technology Dependency Injection (DI) is a great way to reduce tight coupling between software components. Instead of hard-coding dependencies, such as specifying a database driver, you make those connections through a third party. Central to application frameworks like ASP.NET Core, DI enables you to better manage changes and other complexity in your software. About the Book Dependency Injection Principles, Practices, and Patterns is a revised and expanded edition of the bestselling classic Dependency Injection in .NET. It teaches you DI from the ground up, featuring relevant examples, patterns, and anti-patterns for creating loosely coupled, well-structured applications. The well-annotated code and diagrams use C# examples to illustrate principles that work flawlessly with modern object-oriented languages and DI libraries. What's Inside Refactoring existing code into loosely coupled code DI techniques that work with statically typed OO languages Integration with common .NET frameworks Updated examples illustrating DI in .NET Core About the Reader For intermediate OO developers. About the Authors Mark Seemann is a programmer, software architect, and speaker who has been working with software since 1995, including six years with Microsoft. Steven van Deursen is a seasoned .NET developer and architect, and the author and maintainer of the Simple Injector DI library. Table of Contents PART 1 Putting Dependency Injection on the map Chapter 1. The Basics Of Dependency Injection: What, Why, And How Chapter 2. Writing Tightly Coupled Code Chapter 3. Writing Loosely Coupled Code PART 2 Catalog Chapter 1. Di Patterns Chapter 2. Di Anti-Patterns Chapter 3. Code Smells PART 3 Pure DI Chapter 1. Application Composition Chapter 2. Object Lifetime Chapter 3. Interception Chapter 4. Aspect-Oriented Programming By Design Chapter 5. Tool-Based Aspect-Oriented Programming PART 4 DI Containers Chapter 1. Di Container Introduction Chapter 2. The Autofac Di Container Chapter 3. The Simple Injector Di Container Chapter 4. The Microsoft.Extensions.Dependencyinjection Di Container
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值