依赖注入(Dependency Injection)

 

  •  
    • Type 1 or interface injection, in which the exported module provides an interface that its users must implement in order to get the dependencies at runtime (as introduced by Borland Delphi and followed up by C++Builder and JBuilder[citation needed]).
    • Type 2 or setter injection, in which the dependent module exposes a setter method which the framework uses to inject the dependency.
    • Type 3 or constructor injection, in which the dependencies are provided through the class constructor. This is the main form used by PicoContainer, although it also supports setter injection.
    • 类型1 接口注入,外部模块提供一个接口,使用者必须实现此接口以在运行期得到依赖项(Borland Delphi引入,并在C++ BuilderJBuilder中继续运用)。
    • 类型2 设置器注入,使用者暴露一个设置器方法,框架将使用此方法注入依赖项。
    • 类型3 构造器注入,依赖项通过类构造函数提供。这是PicoContainer使用的主要方式(尽管它同时也支持设置器注入)。
  • Dependency injection

    依赖注入

    From Wikipedia, the free encyclopedia

    Jump to: navigation, search

    This article is about article is about the computing process. For other uses, see DI.

    It has been suggested that Dependency inversion principle be merged into this article or section. (Discuss)

    This article or section includes a list of references or external links, but its sources remain unclear because it lacks inline citations.

    You can improve this article by introducing more precise citations where appropriate. (October 2007)

    Dependency injection (DI) in Computer programming refers to the process of supplying an external dependency to a software component. It is a specific form of inversion of control where the concern being inverted is the process of obtaining the needed dependency.

    计算机程序设计中的依赖注入(DI指的是将一个外部依赖项提供给一个软件组件的过程。这是一种特殊形式的控制反转,其中反转的关注点是获得需要的依赖项的处理。

     

    Conventionally, if an object needs to gain access to a particular service, the object takes responsibility to get hold of that service: either it holds a direct reference to the location of that service, or it goes to a known 'service locator' and requests that it be passed back a reference to an implementation of a specified type of service. By contrast, using dependency injection, the object simply provides a property that can hold a reference to that type of service; and when the object is created a reference to an implementation of that type of service will automatically be injected into that property - by an external mechanism.

    通常,如果一个对象要获得对某个特定服务的访问,对象自己将负责获得这个服务:要么此对象有对这个服务位置的直接引用,要么此对象向一个已知的‘服务定位器’发出请求以得到一个对于特定类型服务实现的引用。与之相对,使用依赖注入,对象只需要简单的提供一个类型,这个类型包含找到某种服务的引用,当对象被创建时,这个引用就可以被一个外部机制自动注入此对象的这个属性里.

     

    When the dependency injection technique is used to decouple high-level modules from low-level services, the resulting design guideline is called the Dependency inversion principle.

    在依赖注入技术开始被用于将高层模块与底层服务解耦的过程中,产生了被称为“依赖倒置原则”的设计准则

     

    The dependency injection approach offers more flexibility because it becomes easier to create alternative implementations of a given service type, and then to specify which implementation is to be used via a configuration file, without any change to the objects that use the service. This is especially useful in unit testing, because it is easy to inject a mock implementation of a service into the object being tested. On the other hand, excessive use of dependency injection can make applications more complex and harder to maintain: in order to understand the application's behaviour the developer needs to look at the configuration as well as the code, and the configuration is "invisible" to IDE-supported reference analysis and refactoring unless the IDE specifically supports the dependency injection framework.

    依赖注入使设计更加灵活。我们可以更容易创建给定服务类型的可选实现,并无需改动使用此服务的对象,仅通过配置文件就可以指定使用哪一个实现。由于可以非常容易的把一个模仿实现注入到被测试对象中,依赖注入技术在单元测试中非常有用。但是,过多的使用依赖注入将会令应用程序更加复杂而难于维护:为了理解应用程序的行为,除了阅读代码,开发人员还必须察看配置文件,然而,配置文件往往对于IDE提供的引用分析和重构机制不可见(除非IDE对依赖注入框架提供了特别的支持)。

    Contents

    目录

    [hide]

    A code illustration using Java

    JAVA代码示例

     

    Suppose that IFoo is an interface:

    假设IFoo是一个接口

    public interface IFoo
    {
          void bar(); // Perform bar
          void baz(); // Perform baz
    }

    There exist also a number of implementation classes, each of them implementing IFoo in some way:

    还有一些实现类,每一个都用不同方式实现了IFoo

    public class DatabaseFoo
          implements IFoo
    {
          void bar()
          {
              Database.selectBar().execute(); // Use the database to do bar
          }
     
          void baz()
          {
              Database.selectBaz().run(); // Use the database to do baz
          }
    }

    public class PixieDustFoo
          implements IFoo
    {
          void bar()
          {
              Spell.cast("bar"); // Magic!
          }
     
          void baz()
          {
              Spell.cast("baz"); // Magic!
          }
    }

    public class EnterpriseFoo
          implements IFoo
    {
          void bar()
          {
                EnterpriseFactoryObserverFactoryCreator efofc = new EnterpriseFactoryObserverFactoryCreator("bar");
                efofc.creatify();
                efofc.preparify();
                efofc.configurise();
                efofc.makeAwardWinning();
                efofc.opportunities.leverage();
          }
     
          void baz()
          {
                EnterpriseFactoryObserverFactoryCreator efofc = new EnterpriseFactoryObserverFactoryCreator("baz");
                efofc.creatify();
                efofc.preparify();
                efofc.configurise();
                efofc.makeAwardWinning();
                efofc.opportunities.leverage();
          }
    }

    IFoo only specifies the operations available in its interface, but doesn't itself provide any implementation, instead leaving that to other implementer classes. This way a user wishing to use the IFoo functionality can use any implementation, not knowing anything more about them than that they conform to the Foo interface.

    IFoo仅仅指定了这个接口可以进行的操作,但并没有提供任何实现,而是留给了其它实现者的类。这样当一个用户希望使用IFoo功能,就可以使用任何一个实现,除了知道它们都遵守IFoo接口外,不需要事前知道任何更多的细节。

     

    An object needing the services defined by IFoo needs to get an instance of a class that implements IFoo:

    一个需要使用IFoo定义的服务的对象,需要得到一个实现IFoo的类的实例:

     

    public class ImportantClass {
          IFoo foo;
     
          public ImportantClass()
          {
                this.foo = new EnterpriseFoo();
          }
     
          void doReallyImportantStuff()
          {
                this.foo.bar();
          }
    }

    However, this defeats the entire point of using an interface instead of a concrete implementation. To fix that, it's enough to let the outside caller provide the desired implementation:

    但是,这完全破坏了使用接口而不是一个具体实现的目标。为修正这个问题,让外部调用者提供所需的实现就足可以满足目标了。

     

    public ImportantClass(IFoo foo)
    {
        this.foo = foo;
    }

    When using dependency injection there is usually a configuration mechanism or architecture for deciding which implementation gets injected into an object.

    当使用依赖注入时,通常会有一个配置机制或是某个特定架构,以决定哪个实现将被注入到一个对象中。

     

    Forms of Dependency Injection

    依赖注入的几种形式

     

    Martin Fowler identifies three ways in which an object can get a reference to an external module, according to the pattern used to provide the dependency:

    依照提供依赖项时使用的模式,Martin Fowler定义了三种对象可以从得到一个外部模块引用的方式:

     

     

    The open source Yan Container[1] provides support for arbitrary types of injection[2] besides the common ones defined above.

    除了前列的几种普通形式外,开源项目Yan Container还对任意形式的注入提供了支持。

     

    Existing frameworks

    现有框架

     

    Dependency injection frameworks exist for a number of platforms and languages including:

    在一些平台和语言中都有依赖注入框架,包括:

    ActionScript

    C++

    ColdFusion

    Delphi

    Java

    Java 2 Micro Edition

    .NET

    PHP4

    PHP5

    Perl

    Python

    Ruby

    See also

    参见

     

    External links

    外部链接

    Retrieved from "http://en.wikipedia.org/wiki/Dependency_injection"

    Categories: Software components | Software architecture

    Hidden categories: Articles to be merged since June 2008 | Articles lacking in-text citations | All articles with unsourced statements | Articles with unsourced statements since July 2008

     

    源文档 <http://en.wikipedia.org/wiki/Dependency_injection>

     

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、付费专栏及课程。

余额充值