Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Dependency injection in Scala: Constructors and...

Dependency injection in Scala: Constructors and cakes

A look at two methods of dependency injection in Scala. DIY approach with constructor injection and the cake pattern.

Jan Fredrik Wedén

November 02, 2011
Tweet

More Decks by Jan Fredrik Wedén

Other Decks in Programming

Transcript

  1. Abstract  (type)  members   trait SomeComponent { type T <:

    SomeInterface def methodThing: SomeInterface val aThing: SomeInterface trait SomeInterface { // Stuff } }  
  2. Self  type  annota+ons   trait AnotherComponentImpl extends AnotherComponent { this:

    SomeComponent => val aThing = new SomeInterfaceImpl class AnotherInterfaceImpl extends AnotherInterface { // Impl stuff } }  
  3. Modular  mixin  composi+on   object ComponentRegistry extends SomeComponentImpl with AnotherComponentImpl

    ... val myThing = ComponentRegistry.aThing new SomeComponentImpl with AnotherComponent { val aThing = new FavouriteImpl(‘a parameter’) }  
  4. Modular  mixin  composi+on   trait TestComponentRegistry extends SomeComponentImpl with AnotherComponentImpl

    with org.specs.mock.JMocker { val aThing = mock(classof[SomeInterface]) }
  5. trait SomeComponent { val aThing: SomeInterface trait SomeInterface { //

    Stuff } } trait AnotherComponentImpl extends AnotherComponent { this: SomeComponent => def myMethod { aThing.usefulStuff() } }   object ComponentRegistry extends AnotherComponentImpl with SomeComponentImpl { val aThing = new MyFavouriteImpl }
  6. Credits   •  “Dependency  Injec+on  Op+ons  in  Scala”  –  Dick

     Wall  @  JavaZone  X  2011   –  h6p://vimeo.com/28792660   •  “Scalable  Component  Abstrac+ons”  –  Mar+n  Odersky,  Ma6hias  Zenger   –  h6p://lamp.epfl.ch/~odersky/papers/ScalableComponent.pdf   •  “Real-­‐World  Scala:  Dependency  Injec+on  (DI)”  –  Jonas  Bonér   –  h6p://jonasboner.com/2008/10/06/real-­‐world-­‐scala-­‐dependency-­‐injec+on-­‐ di.html   •  “Do  it  Yourself  –  Dependency  Injec+on”  –  Miško  Hevery/Chad  Parry   –  h6p://misko.hevery.com/2010/05/26/do-­‐it-­‐yourself-­‐dependency-­‐injec+on/   •  “Slicing  the  cake”  –  Przemek  Pokrywka   –  h6p://biased-­‐and-­‐fair-­‐solware-­‐development.blogspot.com/2011/01/slicing-­‐ cake.html   •  “Dependency  Injec+on  in  Scala:  Extending  the  Cake  Pa6ern”  –  Adam  Warski   –  h6p://www.warski.org/blog/2010/12/di-­‐in-­‐scala-­‐cake-­‐pa6ern/   •  “DI  in  Scala:  Cake  Pa6ern  pros  &  cons”  –  Adam  Warski   –  h6p://www.warski.org/blog/2011/04/di-­‐in-­‐scala-­‐cake-­‐pa6ern-­‐pros-­‐cons/  
  7. BEKK CONSULTING AS SKUR 39, VIPPETANGEN. P.O. BOX 134 SENTRUM,

    0102 OSLO, NORWAY. WWW.BEKK.NO Jan  Fredrik  Wedén   Manager,  Trondheim   @jfweden