Dependency Injection

Dependency Injection

Dependency injection In software engineering, dependency injection is a something we don't even have or which has expired. software design pattern that implements inversion of con- What you should be doing is stating a need, “I need some- trol for resolving dependencies. thing to drink with lunch,” and then we will make sure you Dependency injection means giving an object its instance have something when you sit down to eat. variables. Really. That’s it. John Munsch, 28 October 2009.[4][5][6] James Shore, 22 March 2006.[1] Dependency injection separates the creation of a client’s A dependency is an object that can be used (a service). dependencies from the client’s behavior, which allows An injection is the passing of a dependency to a depen- program designs to be loosely coupled[7] and to follow dent object (a client) that would use it. The service is the dependency inversion and single responsibility prin- made part of the client’s state.[1] Passing the service to ciples.[4][8] It directly contrasts with the service locator the client, rather than allowing a client to build or find the pattern, which allows clients to know about the system service, is the fundamental requirement of the pattern. they use to find dependencies. “Don't call us, we'll call you” An injection, the basic unit of dependency injection, is Hollywood Principle.[2] not a new or a custom mechanism. It works the same way that "parameter passing" works.[9] Referring to “parame- ter passing” as an injection carries the added implication Dependency injection allows a program design to follow that it’s being done to isolate the client from details. the dependency inversion principle. The client delegates to external code (the injector) the responsibility of pro- An injection is also about what is in control of the pass- viding its dependencies. The client is not allowed to call ing (never the client) and is independent of how the pass- ing is accomplished, whether by passing a reference or a the injector code.[2] It is the injecting code that constructs the services and calls the client to inject them. This means pointer. the client code does not need to know about the injecting Dependency injection involves four roles: code. The client does not need to know how to construct the services. The client does not need to know which ac- • the service object(s) to be used tual services it is using. The client only needs to know • the client object that is depending on the services it about the intrinsic interfaces of the services because these uses define how the client may use the services. This separates the responsibilities of use and construction. • the interfaces that define how the client may use the There are three common means for a client to accept a services dependency injection: setter-, interface- and constructor- • the injector, which is responsible for constructing based injection. Setter and constructor injection differ the services and injecting them into the client mainly by when they can be used. Interface injection dif- fers in that the dependency is given a chance to control Any object that may be used can be considered a service. its own injection. All require that separate construction Any object that uses other objects can be considered a code (the injector) take responsibility for introducing a client. The names have nothing to do with what the ob- [3] client and its dependencies to each other. jects are for and everything to do with the role the objects play in any one injection. The interfaces are the types the client expects its depen- 1 Overview dencies to be. At issue is what they make accessible. They may truly be interface types implemented by the services but also may be abstract classes or even the concrete ser- Dependency injection for five-year-olds vices themselves, though this last would violate DIP[10] When you go and get things out of the refrigerator for and sacrifice the dynamic decoupling that enables test- yourself, you can cause problems. You might leave the ing. It’s only required that the client does not know which door open, you might get something Mommy or Daddy they are and therefore never treats them as concrete, say doesn't want you to have. You might even be looking for by constructing or extending them. 1 2 1 OVERVIEW Given that the client has no concrete knowledge, so long • Dependency injection can be used to externalize a as the what the client uses, the interfaces name and API system’s configuration details into configuration files then the client wont need to change even if what is be- allowing the system to be reconfigured without re- hind the interface changes. However, if the interface is compilation. Separate configurations can be written refactored from being a class to an interface type (or vise for different situations that require different imple- versa) the client will need to be recompiled.[11] This is mentations of components. This includes, but is not significant if the client and services are published sepa- limited to, testing. rately. This unfortunate coupling is one that dependency • Because dependency injection doesn't require any injection cannot resolve. change in code behavior it can be applied to legacy The injector introduces the services into the client. Of- code as a refactoring. The result is clients that are ten, it also constructs the client. An injector may connect more independent and that are easier to unit test in together a very complex object graph by treating an ob- isolation using stubs or mock objects that simulate ject like a client and later as a service for another client. other objects not under test. This ease of testing The injector may actually be many objects working to- is often the first benefit noticed when using depen- gether but may not be the client. The injector may be dency injection. referred to by other names such as: assembler, provider, container, factory, builder, spring, construction code, or • Dependency injection allows a client to remove main. all knowledge of a concrete implementation that it Dependency injection can be applied as a discipline. One needs to use. This helps isolate the client from the that asks that all objects separate construction and be- impact of design changes and defects. It promotes [20] havior. Relying on a DI framework to perform construc- reusability, testability and maintainability. tion can lead to forbidding the use of the new keyword, • or, less strictly, only allow direct construction of value Reduction of boilerplate code in the application ob- objects.[12][13][14][15] jects since all work to initialize or set up dependen- cies is handled by a provider component.[20] 1.1 Taxonomy • Dependency injection allows concurrent or indepen- dent development. Two developers can indepen- Inversion of Control (IoC) is more general than DI. Put dently develop classes that use each other, while only simply IoC means letting other code call you rather than needing to know the interface the classes will com- insisting on doing the calling. An example of IoC with- municate through. Plugins are often developed by out DI is the template pattern. Here polymorphism is third party shops that never even talk to the devel- achieved through subclassing, that is, inheritance.[16] opers who created the product that uses the plugins. Dependency injection implements IoC through • Dependency Injection decreases coupling between a composition so is often identical to that of the strategy class and its dependency.[21][22] pattern, but while the strategy pattern is intended for dependencies to be interchangeable throughout an object’s lifetime, in dependency injection it may be that 1.4 Disadvantages only a single instance of a dependency is used.[17] This still achieves polymorphism, but though delegation and • Dependency injection creates clients that demand composition. configuration details be supplied by construction code. This can be onerous when obvious defaults are available. 1.2 Frameworks • Dependency injection can make code difficult to Application frameworks such as Spring, Guice, Play trace (read) because it separates behavior from con- framework, Salta, Glassfish HK2, and Microsoft Man- struction. This means developers must refer to more aged Extensibility Framework (MEF) support depen- files to follow how a system performs. dency injection but are not required to do dependency • injection.[18][19] Dependency injection typically requires more up- front development effort since one can not sum- mon into being something right when and where it 1.3 Advantages is needed but must ask that it be injected and then ensure that it is injected. • Dependency injection allows a client the flexibility of being configurable. Only the client’s behavior is • Dependency injection can cause an explosion of fixed. The client may act on anything that supports types, especially in languages that have explicit in- the intrinsic interface the client expects. terface types, like Java and C# [23] 2.2 Three types of dependency injection 3 • Dependency injection forces complexity to move clients actively accept dependency injection thus mak- out of classes and into the linkages between classes ing legacy code testable. In particular, in the java lan- which might not always be desirable or easily guage it is possible to use reflection to make private at- managed.[24] tributes public when testing and thus accept injections by assignment.[29] • Ironically, dependency injection can encour- Some attempts at Inversion of Control do not provide full age dependence on a dependency injection removal of dependency but instead simply substitute one [24][25][26] framework. form of dependency for another. As a rule of thumb, if a programmer can look at nothing but the client code and tell what framework is being used, then the client has a 2 Examples hard-coded dependency on the framework.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    8 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us