In , dependency injection is a something we don't even have or which has expired. 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-, - 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- , 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- (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 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.

2.1 Without dependency injection 2.2.2 Constructor injection In the following Java example, the Client class contains a This method requires the client to provide a parameter in Service member variable that is initialized by the Client a constructor for the dependency. constructor. The client controls which implementation of service is used and controls its construction. In this situ- // Constructor Client(Service service) { // Save the ation, the client is said to have a hard-coded dependency reference to the passed-in service inside this client on ServiceExample. this.service = service; } // An example without dependency injection public class Client { // Internal reference to the service used by this client private Service service; // Constructor Client() { 2.2.3 Setter injection // Specify a specific implementation in the constructor instead of using dependency injection this.service = new This method requires the client to provide a setter method ServiceExample(); } // Method within this client that for each dependency. uses the services public String greet() { return “Hello " + // Setter method public void setService(Service service) service.getName(); } } { // Save the reference to the passed-in service inside this client this.service = service; } Dependency injection is an alternative technique to ini- tialize the member variable than explicitly creating a ser- vice object as shown above. 2.2.4 Interface injection

2.2 Three types of dependency injection This is simply the client publishing a role interface to the setter methods of the client’s dependencies. It can be used There are at least three ways an object can receive a ref- to establish how the injector should talk to the client when erence to an external module:[27] injecting dependencies. // Service setter interface. public interface ServiceSetter • constructor injection: the dependencies are provided { public void setService(Service service); } // Client through a class constructor. class public class Client implements ServiceSetter { • setter injection: the client exposes a setter method // Internal reference to the service used by this client. that the injector uses to inject the dependency. private Service service; // Set the service that this client is to use. @Override public void setService(Service • interface injection: the dependency provides an in- service) { this.service = service; } } jector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency. 2.2.5 Constructor injection comparison

Preferred when all dependencies can be constructed first 2.2.1 Other types because it can be used to ensure the client object is al- ways in a valid state, as opposed to having some of its It is possible for DI frameworks to have other types of [28] dependency references be null (not be set). However, on injection beyond those presented above. its own, it lacks the flexibility to have its dependencies Testing frameworks may also use other types. Some changed later. This can be a first step towards making modern testing frameworks do not even require that the client immutable and therefore thread safe. 4 2 EXAMPLES

// Constructor Client(Service service, Service oth- An assembler is still needed to introduce the client and erService) { if (service == null) { throw new Invalid- its dependencies. The assembler would take a reference ParameterException(“service must not be null”); } if to the client, cast it to the setter interface that sets that (otherService == null) { throw new InvalidParameterEx- dependency, and pass it to that dependency object which ception(“otherService must not be null”); } // Save the would turn around and pass a reference-to-self back to service references inside this client this.service = service; the client. this.otherService = otherService; } For interface injection to have value, the dependency must do something in addition to simply passing back a reference to itself. This could be acting as a factory 2.2.6 Setter injection comparison or sub-assembler to resolve other dependencies, thus ab- stracting some details from the main assembler. It could Requires the client to provide a setter method for each be reference-counting so that the dependency knows how dependency. This gives the freedom to manipulate the many clients are using it. If the dependency maintains a state of the dependency references at any time. This of- collection of clients, it could later inject them all with a fers flexibility, but if there is more than one dependency different instance of itself. to be injected, it is difficult for the client to ensure that all dependencies are injected before the client could be provided for use. 2.3 Assembling examples

// Set the service to be used by this client public void Manually assembling in main by hand is one way of im- setService(Service service) { if (service == null) { plementing dependency injection. throw new InvalidParameterException(“service must not be null”); } this.service = service; } // Set the other public class Injector { public static void main(String[] service to be used by this client public void setOtherSer- args) { // Build the dependencies first Service service = vice(Service otherService) { if (otherService == null) new ServiceExample(); // Inject the service, constructor { throw new InvalidParameterException(“otherService style Client client = new Client(service); // Use the must not be null”); } this.otherService = otherService; } objects System.out.println(client.greet()); } }

Since these injections happen independently there is no The example above constructs the object graph manually way to tell when the injector is finished wiring the client. and then invokes it at one point to start it working. Impor- A dependency can be left null simply by the injector fail- tant to note is that this injector is not pure. It uses one of ing to call its setter. This forces the check that injec- the objects it constructs. It has a purely construction-only tion was completed from when the client is assembled to relationship with ServiceExample but mixes construction whenever it is used. and using of Client. This should not be common. It is, however, unavoidable. Just like object oriented software // Set the service to be used by this client public void set- needs a non-object oriented static method like main() to Service(Service service) { this.service = service; } // Set get started, a dependency injected object graph needs at the other service to be used by this client public void se- least one (preferably only one) to get the using tOtherService(Service otherService) { this.otherService started. = otherService; } // Check the service references of this client private void validateState() { if (service == Manual construction in the main method may not be null) { throw new IllegalStateException(“service must this straight forward and may involve calling builders, not be null”); } if (otherService == null) { throw new factories, or other construction as well. This can IllegalStateException(“otherService must not be null”); be fairly advanced and abstract. The line is crossed from } } // Method that uses the service references public void manual dependency injection to framework dependency doSomething() { validateState(); service.doYourThing(); injection once the constructing code is no longer custom otherService.doYourThing(); } to the application and is instead universal.[30] Frameworks like Spring can construct these same objects and wire them together before returning a reference to client. Notice that all mention of ServiceExample has 2.2.7 Interface injection comparison been removed from the code. The advantage of interface injection is that dependencies import org.springframework.beans.factory.BeanFactory; can be completely ignorant of their clients yet can still import org.springframework.context.ApplicationContext; receive a reference to a new client and, using it, send a import org.springframework.context.support.ClassPathXmlApplicationContext; reference-to-self back to the client. In this way, the de- public class Injector { public static void pendencies become injectors. The key is that the inject- main(String[] args) { // -- Assembling ob- ing method (which could just be a classic setter method) jects -- // BeanFactory beanfactory=new Class- is provided through an interface. PathXmlApplicationContext(“Beans.xml”); Client 2.4 Assembly comparison 5 client=(Client)beanfactory.getBean(“client”); // -- Using @ComponentScan static class MyConfiguration { objects -- // System.out.println( client.greet() ); } } @Bean public Client client(ServiceExample service) { return new Client(service); } } Frameworks like Spring allow assembly details to be @Component public class ServiceExample { public externalized in configuration files. This code (above) String getName() { return “World!"; } } constructs objects and wires them together according to Beans.xml (below). ServiceExample is still constructed even though it’s only mentioned below. A long and com- 2.4 Assembly comparison plex object graph can be defined this way and the only class mentioned in code would be the one with the entry The different injector implementations (factories, service point method, which in this case is greet(). locators, and dependency injection containers) are not that different as far as dependency injection is concerned.

Create a new injector that can provide components de- [4] Seeman, Mark (October 2011). Dependency Injec- fined in the myModule module and request our greeter tion in .NET. Manning Publications. p. 4. ISBN service from the injector. (This is usually done automat- 9781935182504. ically by the AngularJS bootstrap). [5] “Dependency Injection in NET” (PDF). http://philkildea. var injector = angular.injector(['myModule', 'ng']); var co.uk''. p. 4. Retrieved 2015-07-18. greeter = injector.get('greeter'); [6] “How to explain dependency injection to a 5-year-old?". stackoverflow.com. Retrieved 2015-07-18. Asking for dependencies solves the issue of hard coding, but it also means that the injector needs to be passed [7] Seemann, Mark. “Dependency Injection is Loose Cou- pling”. blog.ploeh.dk. Retrieved 2015-07-28. throughout the application. Passing the injector breaks the Law of Demeter. To remedy this, we use a declara- [8] Niko Schwarz, Mircea Lungu, Oscar Nierstrasz, “Seuss: tive notation in our HTML templates, to hand the respon- Decoupling responsibilities from static methods for fine- sibility of creating components over to the injector, as in grained configurability”, Journal of Object Technology, this example: Volume 11, no. 1 (April 2012), pp. 3:1-23

function Java™ Tutorials > Learning the Java Language > Classes MyController($scope, greeter) { $scope.sayHello = and Objects)". docs.oracle.com. Retrieved 2015-07-18. function() { greeter.greet('Hello World'); }; } [10] “A curry of Dependency Inversion Principle (DIP), Inver- sion of Control (IoC), Dependency Injection (DI) and IoC When AngularJS compiles the HTML, it processes the Container - CodeProject”. www.codeproject.com. Re- ng-controller directive, which in turn asks the injector to trieved 2015-08-08. create an instance of the controller and its dependencies. [11] “How to force “program to an interface” without injector.instantiate(MyController); using a java Interface in java 1.6”. program- This is all done behind the scenes. Notice that by having mers.stackexchange.com. Retrieved 2015-07-19. the ng-controller ask the injector to instantiate the class, it [12] “To “new” or not to “new"…". Retrieved 2015-07-18. can satisfy all of the dependencies of MyController with- out the controller ever knowing about the injector. This is [13] “How to write testable code”. www.loosecouplings.com. the best outcome. The application code simply declares Retrieved 2015-07-18. the dependencies it needs, without having to deal with the injector. This setup does not break the Law of Demeter. [14] “Writing Clean, Testable Code”. www.ethanresnick.com. Retrieved 2015-07-18. 7

[15] Sironi, Giorgio. “When to inject: the distinction be- [36] Morling, Gunnar (2012-11-18). “Dagger - A new Java tween newables and injectables - Invisible to the eye”. dependency injection framework”. Dagger - A new Java www.giorgiosironi.com. Retrieved 2015-07-18. dependency injection framework - Musings of a Program- ming Addict. Retrieved 2015-07-18. [16] “Inversion of Control vs Dependency Injection”. stack- overflow.com. Retrieved 2015-08-05. [37] “The Java Community Process(SM) Program - JSRs: Java Specification Requests - detail JSR# 330”. www.jcp.org. [17] “What is the difference between Strategy pattern and Retrieved 2015-07-18. Dependency Injection?". stackoverflow.com. Retrieved 2015-07-18. [18] “Dependency Injection != using a DI container”. www. 5 External links loosecouplings.com. Retrieved 2015-07-18.

[19] “Black Sheep » DIY-DI » Print”. blacksheep.parry.org. • A beginners guide to Dependency Injection Retrieved 2015-07-18. • Dependency Injection & Testable Objects: Design- [20] “The Java Community Process(SM) Program - JSRs: Java ing loosely coupled and testable objects - Jeremy Specification Requests - detail JSR# 330”. jcp.org. Re- Weiskotten; Dr. Dobb’s Journal, May 2006. trieved 2015-07-18. • : Dependency Injection -- MSDN [21] “the urban canuk, eh: On Dependency Injection and Vi- Magazine, September 2005 olating Encapsulation Concerns”. www.bryancook.net. Retrieved 2015-07-18. • Martin Fowler’s original article that introduced the [22] “The Dependency Injection ”. term Dependency Injection msdn.microsoft.com. Retrieved 2015-07-18. • P of EAA: Plugin [23] “What are the advantages and disadvantages when we are • implementing the dependency injection? - Quora”. www. The Rich Engineering Heritage Behind Dependency quora.com. Retrieved 2015-07-18. Injection - Andrew McVeigh - A detailed history of dependency injection. [24] “What are the downsides to using Dependency Injec- tion?". stackoverflow.com. Retrieved 2015-07-18. • What is Dependency Injection? - An alternative ex- planation - Jakob Jenkov [25] “Dependency Injection Inversion - Clean Coder”. sites.google.com. Retrieved 2015-07-18. • Writing More Testable Code with Dependency In- jection -- Developer.com, October 2006 [26] “Decoupling Your Application From Your Dependency Injection Framework”. InfoQ. Retrieved 2015-07-18. • Managed Extensibility Framework Overview -- [27] Martin Fowler (2004-01-23). “Inversion of Control Con- MSDN tainers and the Dependency Injection pattern - Forms of • Old fashioned description of the Dependency Mech- Dependency Injection”. Martinfowler.com. Retrieved 2014-03-22. anism by Hunt 1998

[28] “Yan - Dependency Injection Types”. Yan.codehaus.org. • Refactor Your Way to a Dependency Injection Con- Retrieved 2013-12-11. tainer

[29] “AccessibleObject (Java Platform SE 7 )". docs.oracle.com. Retrieved 2015-07-18.

[30] Riehle, Dirk (2000), Framework Design: A Role Modeling Approach (PDF), Swiss Federal Institute of Technology

[31] “Spring Tips: A POJO with annotations is not Plain”. Re- trieved 2015-07-18.

[32] “Annotations in POJO – a boon or a curse? | Techtracer”. Retrieved 2015-07-18.

[33] “Pro Spring Dynamic Modules for OSGi Service Plat- forms”. APress. Retrieved 2015-07-06.

[34] “Captain Debug’s Blog: Is ‘Convention Over Configu- ration’ Going Too Far?". www.captaindebug.com. Re- trieved 2015-07-18.

[35] Decker, Colin. “What’s the issue with @Inject? | Colin’s Devlog”. blog.cgdecker.com. Retrieved 2015-07-18. 8 6 TEXT AND IMAGE SOURCES, CONTRIBUTORS, AND LICENSES

6 Text and image sources, contributors, and licenses

6.1 Text

• Dependency injection Source: https://en.wikipedia.org/wiki/Dependency_injection?oldid=679400152 Contributors: Sjc, William Av- ery, Frecklefoot, Kku, HarmonicSphere, Julesd, Ehn, Timwi, Sbwoodside, Doradus, Amphioxys, RickBeton, Fredrik, RedWolf, Lum- ingz, Tobias Bergemann, Nelson Minar, Sepreece, Kevinb9n, Khalid hassani, Neilc, Beland, Oneiros, TreyHarris, Andreas Kaufmann, Mathieu, Kjkolb, Franl, Diego Moya, Chuck Adams, RoySmith, Dionyziz, Justin Ormont, MizardX, Tlroche, Emrysk, FlaBot, Kolbasz, Riki, Mathrick, Frappyjohn, Dkg, Bgwhite, Peterl, YurikBot, Angus Lepper, ChristianEdwardGruber, RsRado, Sikon, RL0919, Kev- inTeague, MySchizoBuddy, Leotohill, CWenger, Brian428, Funkatron, SmackBot, FlashSheridan, NickHodges, PeterProvost, Chris the speller, Jadriman, Janvo, Frap, Cybercobra, Andrew c, Daniel.Cardenas, KenFehling, Hulmem, Loadmaster, Wikidrone, Gregturn, Mike Fikes, Keredson, Kicolobo~enwiki, Chadh, FatalError, Errandir, Cydebot, BruceHaley, AndyGavin, Ebyabe, Towopedia, Nick Num- ber, Jaxelrod, Kristoferhoch, Nosbig, ThomasO1989, Filnik, Magioladitis, JamesBWatson, Bernd vdB~enwiki, Donsez, PongGod, Yaron K., Wild Pansy, LedgendGamer, Derekgreer, DotNetGuy, Elpecek, GDW13, Sigmundur, STBotD, HighKing, WhiteOak2006, BBilge, Mistercupcake, VolkovBot, The Wild Falcon, MatisseEnzer, Shangri67, Wingedsubmariner, Pitchers, Michaeldsuarez, Steinhb, Ramiro- magalhaes, Avegas, Clement.escoffier, Mongbei, Flyer22, Nkohari, Souter, DexM~enwiki, PabloStraub, Btp1021, GrandOpener, Rpaw- son, Gstar42, Konsumkind, SetaLyas, Fbrown649, DEfusion, Jusdafax, Ye-thorn, Doublecompile, Cristiandeidaho, SteveMao, Aprock, Kjin101, Jjenkov2, 1ForTheMoney, Neverhood311, XLinkBot, Pandrija, Aparraga, Addbot, Mortense, Zeflasher, Ironholds, Btx40, MrOl- lie, Sgrundsoe, Cemsbr, Ekameleon, SpBot, Bender2112, Jjdawson7, Jarble, Luckas-bot, Yobot, AnomieBOT, Joule36e5, Digulla, Piano non troppo, Edrowland, Neurolysis, ArthurBot, Peter lawrey, Jelaplan, Anna Frodesiak, Lastcraft, Rodbeck~enwiki, Tabledhote, Pe- ter.c.grant, FrescoBot, Sae1962, Polaroidforever, SpaceFlight89, Datoine, Ru1fdo, CH3374H, Torabli, Jeroen De Dauw, Mfurr, Lotje, Hfrmobile, Ottomachin, Oliverlyc, Joshuatbrown, WikitanvirBot, Hanavy, JamesCrook, Dewritech, Arkenflame, Nachinius, Dotcomsoft- ware, Jrw1234, ClueBot NG, Ndroock1, Jjcolosi, Candace Gillhoolley, Introw, Ekphraster, Helpful Pixie Bot, Datslo, BG19bot, Ency- clopedant, Paul240511, Wolanski.p, My Name is Christopher, Axelock, Udaymummidi, YFdyh-bot, Tysontra, AlecTaylor, Abergquist, Michaeloryl, Man8, DarioFixe, Rjacquier, Shairez, Emilymab, Urbancenter, Akosiaris, TheRealHave, Softzen, SJ Defender, Opencooper, Brian.clozel, Ptoumanov, Galhalee, Danny.Smart, Tmklsankar, Gao Jia Siang, Ruediste1, Humbug26, Lphaf and Anonymous: 343

6.2 Images

• File:Commons-logo.svg Source: https://upload.wikimedia.org/wikipedia/en/4/4a/Commons-logo.svg License: ? Contributors: ? Original artist: ?

6.3 Content license

• Creative Commons Attribution-Share Alike 3.0