SlideShare une entreprise Scribd logo
1  sur  21
Télécharger pour lire hors ligne
Hvordan vi klarte oss uten Spring,
  dependency injection i Scala
          Alf Kristian Støyle
          Know IT Objectnet
Dependency Injection
    Transactions
Cake pattern
 ‘Cake Pattern’ because “(...) beyond my
appreciation of cake, [a] cake is made of a
number of layers (separated by jam), and
  can be sliced. The layers represent the
different levels of inner class nesting. It is
   conceivable that you would reach the
 bottom layer by working your way down
                from the top.

  http://scala.sygneca.com/patterns/component-mixins
http://lamp.epfl.ch/~odersky/papers/ScalableComponent.pdf


   http://jonasboner.com/2008/10/06/real-world-scala-
               dependency-injection-di.html
case class User(username: String, password: String)
class UserRepository {
  def authenticate(user: User): User = {
      println("authenticating user: " + user)
      user
    }
  def create(user: User): User = {
      println("creating user: " + user)
      user
  }
}
class UserService {

    val userRepository = new UserRepository

     def authenticate(username: String, password: String): User =
       userRepository.authenticate(new User(username, password))
     def create(username: String, password: String): User =
       userRepository.create(new User(username, password))
}
class UserRepository {
  def authenticate(user: User): User = {
      println("authenticating user: " + user)
      user
    }
  def create(user: User): User = {
      println("creating user: " + user)
      user
  }
}
trait UserRepositoryComponent {

    val userRepository: UserRepository

    class UserRepository {
      def authenticate(user: User): User = {
        println("authenticating user: " + user)
        user
      }
      def create(user: User): User = {
        println("creating user: " + user)
        user
      }
    }
}
class UserService {
  def authenticate(username: String, password: String): User =
    userRepository.authenticate(new User(username, password))
  def create(username: String, password: String): User =
    userRepository.create(new User(username, password))
}
trait UserServiceComponent extends
      UserRepositoryComponent {

//val userRepository: UserRepository
  val userService: UserService

    class UserService {
      def authenticate(username: String, password: String): User =
        userRepository.authenticate(new User(username, password))
      def create(username: String, password: String): User =
        userRepository.create(new User(username, password))
    }
}
trait UserServiceComponent {
      self: UserRepositoryComponent =>

//val userRepository: UserRepository
  val userService: UserService

    class UserService {
      def authenticate(username: String, password: String): User =
        userRepository.authenticate(new User(username, password))
      def create(username: String, password: String): User =
        self.userRepository.create(new User(username, password))
    }
}
object ComponentRegistry extends
  UserServiceComponent with
  UserRepositoryComponent {

    val userRepository = new UserRepository
    val userService = new UserService
}


val userService = ComponentRegistry.userService
val user = userService.authenticate("user", "password")
// => User(user,password)
import org.mockito.Mockito._

class TestingEnvironment extends
  UserServiceComponent with
  UserRepositoryComponent {

    val userRepository = mock(classOf[UserRepository])
    val userService = new UserService
}

val testEnv = new TestingEnvironment
when(testEnv.userRepository
            .authenticate(new User("user", "password")))
            .thenReturn(new User("mock", "mockpwd"))
val userService = testEnv.userService
val user = userService.authenticate("user", "password")
// => User(mock,mockpwd)
Gotchas


• Class vs Object
• Typenavn
Andre måter

• Structural types
• Implicit declarations
• Functional currying
• Spring
• Guice
Transactions
import org.springframework.transaction.annotation.Transactional

class UserService {
	
  @Transactional def create(username: String, password: String) = {
    userRepository.create(new User(username, password))
  }
}
Transactions
import TransactionManager._

class UserService {
	
  def create(username: String, password: String) = transactional {
    userRepository.create(new User(username, password))
  }
}
object TransactionManager {
  def transactional[A](work: => A): A = ...
}
Scala DI
  http://jonasboner.com/2008/10/06/real-world-scala-
              dependency-injection-di.html

       http://programming-scala.labs.oreilly.com/
        ch13.html#DependencyInjectionInScala

http://debasishg.blogspot.com/2011/03/pushing-envelope-
                on-oo-and-functional.html
alf.kristian@gmail.com
http://slideshare.net/stoyle/di-scala
 http://github.com/stoyle/di-scala

Contenu connexe

Tendances

Dependency Injection in Functional Programming
Dependency Injection in Functional ProgrammingDependency Injection in Functional Programming
Dependency Injection in Functional ProgrammingDuana Stanley
 
Rails GUI Development with Ext JS
Rails GUI Development with Ext JSRails GUI Development with Ext JS
Rails GUI Development with Ext JSMartin Rehfeld
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery FundamentalsGil Fink
 
Visual Studio.Net - Sql Server
Visual Studio.Net - Sql ServerVisual Studio.Net - Sql Server
Visual Studio.Net - Sql ServerDarwin Durand
 
えっ、なにそれこわい
えっ、なにそれこわいえっ、なにそれこわい
えっ、なにそれこわいKei Shiratsuchi
 
Building Persona: federated and privacy-sensitive identity for the Web (Open ...
Building Persona: federated and privacy-sensitive identity for the Web (Open ...Building Persona: federated and privacy-sensitive identity for the Web (Open ...
Building Persona: federated and privacy-sensitive identity for the Web (Open ...Francois Marier
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony AppsKris Wallsmith
 
Et si on en finissait avec CRUD ?
Et si on en finissait avec CRUD ?Et si on en finissait avec CRUD ?
Et si on en finissait avec CRUD ?Julien Vinber
 
Informasjonsintegrasjon – hva er utfordringene
Informasjonsintegrasjon – hva er utfordringeneInformasjonsintegrasjon – hva er utfordringene
Informasjonsintegrasjon – hva er utfordringeneStian Danenbarger
 
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Colin O'Dell
 
Coffeescript a z
Coffeescript a zCoffeescript a z
Coffeescript a zStarbuildr
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonKris Wallsmith
 
Windows ストアーアプリで SQLite を使ってみよう
Windows ストアーアプリで SQLite を使ってみようWindows ストアーアプリで SQLite を使ってみよう
Windows ストアーアプリで SQLite を使ってみようShinichiAoyagi
 

Tendances (20)

Dependency Injection in Functional Programming
Dependency Injection in Functional ProgrammingDependency Injection in Functional Programming
Dependency Injection in Functional Programming
 
Rails GUI Development with Ext JS
Rails GUI Development with Ext JSRails GUI Development with Ext JS
Rails GUI Development with Ext JS
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
 
Visual Studio.Net - Sql Server
Visual Studio.Net - Sql ServerVisual Studio.Net - Sql Server
Visual Studio.Net - Sql Server
 
えっ、なにそれこわい
えっ、なにそれこわいえっ、なにそれこわい
えっ、なにそれこわい
 
Jquery
JqueryJquery
Jquery
 
Controle de estado
Controle de estadoControle de estado
Controle de estado
 
Building Persona: federated and privacy-sensitive identity for the Web (Open ...
Building Persona: federated and privacy-sensitive identity for the Web (Open ...Building Persona: federated and privacy-sensitive identity for the Web (Open ...
Building Persona: federated and privacy-sensitive identity for the Web (Open ...
 
Validation
ValidationValidation
Validation
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
Et si on en finissait avec CRUD ?
Et si on en finissait avec CRUD ?Et si on en finissait avec CRUD ?
Et si on en finissait avec CRUD ?
 
Informasjonsintegrasjon – hva er utfordringene
Informasjonsintegrasjon – hva er utfordringeneInformasjonsintegrasjon – hva er utfordringene
Informasjonsintegrasjon – hva er utfordringene
 
Matters of State
Matters of StateMatters of State
Matters of State
 
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016
 
Grails UI Primer
Grails UI PrimerGrails UI Primer
Grails UI Primer
 
Coffeescript a z
Coffeescript a zCoffeescript a z
Coffeescript a z
 
Quanlycanbo
QuanlycanboQuanlycanbo
Quanlycanbo
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-london
 
J query training
J query trainingJ query training
J query training
 
Windows ストアーアプリで SQLite を使ってみよう
Windows ストアーアプリで SQLite を使ってみようWindows ストアーアプリで SQLite を使ってみよう
Windows ストアーアプリで SQLite を使ってみよう
 

En vedette

Cultures:Foreign and Domestic
Cultures:Foreign and DomesticCultures:Foreign and Domestic
Cultures:Foreign and DomesticKdemaio
 
Cultures:Foreign and Domestic
Cultures:Foreign and DomesticCultures:Foreign and Domestic
Cultures:Foreign and DomesticKdemaio
 
Simple machines scavenger hunt
Simple machines scavenger huntSimple machines scavenger hunt
Simple machines scavenger huntdanbel2
 
Bakerfinal
BakerfinalBakerfinal
Bakerfinalbakedizz
 
Ekonomika portów lotniczych w Polsce a problem kosztów zewnętrznych
Ekonomika portów lotniczych w Polsce a problem kosztów zewnętrznychEkonomika portów lotniczych w Polsce a problem kosztów zewnętrznych
Ekonomika portów lotniczych w Polsce a problem kosztów zewnętrznychInstytut Ekonomiki Miast i Regionów
 
Połączenia komunikacyjne z miastem – udział kolei w przygotowaniach do EURO 2...
Połączenia komunikacyjne z miastem – udział kolei w przygotowaniach do EURO 2...Połączenia komunikacyjne z miastem – udział kolei w przygotowaniach do EURO 2...
Połączenia komunikacyjne z miastem – udział kolei w przygotowaniach do EURO 2...Instytut Ekonomiki Miast i Regionów
 
Fossil fuels powerpoint
Fossil fuels powerpointFossil fuels powerpoint
Fossil fuels powerpointdanbel2
 

En vedette (20)

Learning Lisp
Learning LispLearning Lisp
Learning Lisp
 
Barriere secu
Barriere secuBarriere secu
Barriere secu
 
Cultures:Foreign and Domestic
Cultures:Foreign and DomesticCultures:Foreign and Domestic
Cultures:Foreign and Domestic
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Cultures:Foreign and Domestic
Cultures:Foreign and DomesticCultures:Foreign and Domestic
Cultures:Foreign and Domestic
 
Simple machines scavenger hunt
Simple machines scavenger huntSimple machines scavenger hunt
Simple machines scavenger hunt
 
Clojure workshop
Clojure workshopClojure workshop
Clojure workshop
 
Bakerfinal
BakerfinalBakerfinal
Bakerfinal
 
Karma profile
Karma profileKarma profile
Karma profile
 
MODELE BIZNESOWE NA RYNKU PORTÓW LOTNICZYCH...
MODELE BIZNESOWE NA RYNKU PORTÓW LOTNICZYCH...MODELE BIZNESOWE NA RYNKU PORTÓW LOTNICZYCH...
MODELE BIZNESOWE NA RYNKU PORTÓW LOTNICZYCH...
 
Ekonomika portów lotniczych w Polsce a problem kosztów zewnętrznych
Ekonomika portów lotniczych w Polsce a problem kosztów zewnętrznychEkonomika portów lotniczych w Polsce a problem kosztów zewnętrznych
Ekonomika portów lotniczych w Polsce a problem kosztów zewnętrznych
 
Udział kolei w przygotowaniach do EURO 2012 (wrzesień 2008 r.)
Udział kolei w przygotowaniach do EURO 2012 (wrzesień 2008 r.)Udział kolei w przygotowaniach do EURO 2012 (wrzesień 2008 r.)
Udział kolei w przygotowaniach do EURO 2012 (wrzesień 2008 r.)
 
Połączenia komunikacyjne z miastem – udział kolei w przygotowaniach do EURO 2...
Połączenia komunikacyjne z miastem – udział kolei w przygotowaniach do EURO 2...Połączenia komunikacyjne z miastem – udział kolei w przygotowaniach do EURO 2...
Połączenia komunikacyjne z miastem – udział kolei w przygotowaniach do EURO 2...
 
Algorithme
AlgorithmeAlgorithme
Algorithme
 
Fossil fuels powerpoint
Fossil fuels powerpointFossil fuels powerpoint
Fossil fuels powerpoint
 
Sobre a cultura e a personalidade.
Sobre a cultura e a personalidade.Sobre a cultura e a personalidade.
Sobre a cultura e a personalidade.
 
El lenguaje de la vida
El lenguaje de la vidaEl lenguaje de la vida
El lenguaje de la vida
 
Einstein e as maquinas do tempo
Einstein e as maquinas do tempoEinstein e as maquinas do tempo
Einstein e as maquinas do tempo
 
Que é a teoría da relatividade
Que é a teoría da relatividadeQue é a teoría da relatividade
Que é a teoría da relatividade
 
La clave secreta del universo
La clave secreta del universoLa clave secreta del universo
La clave secreta del universo
 

Similaire à Dependency injection in Scala

Dependency injection in Scala
Dependency injection in ScalaDependency injection in Scala
Dependency injection in ScalaKnoldus Inc.
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
Hello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and ClassesHello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and ClassesCody Yun
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsFrancois Zaninotto
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeMacoscope
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languagesRafael Winterhalter
 
Pruebas unitarias con django
Pruebas unitarias con djangoPruebas unitarias con django
Pruebas unitarias con djangoTomás Henríquez
 
Implementation of EAV pattern for ActiveRecord models
Implementation of EAV pattern for ActiveRecord modelsImplementation of EAV pattern for ActiveRecord models
Implementation of EAV pattern for ActiveRecord modelsKostyantyn Stepanyuk
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
The Ring programming language version 1.5.4 book - Part 44 of 185
The Ring programming language version 1.5.4 book - Part 44 of 185The Ring programming language version 1.5.4 book - Part 44 of 185
The Ring programming language version 1.5.4 book - Part 44 of 185Mahmoud Samir Fayed
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkIndicThreads
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Frameworkvhazrati
 
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Leonardo Soto
 
Guard Authentication: Powerful, Beautiful Security
Guard Authentication: Powerful, Beautiful SecurityGuard Authentication: Powerful, Beautiful Security
Guard Authentication: Powerful, Beautiful SecurityRyan Weaver
 

Similaire à Dependency injection in Scala (20)

Django (Web Konferencia 2009)
Django (Web Konferencia 2009)Django (Web Konferencia 2009)
Django (Web Konferencia 2009)
 
Dependency injection in Scala
Dependency injection in ScalaDependency injection in Scala
Dependency injection in Scala
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
Hello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and ClassesHello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and Classes
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
 
Pruebas unitarias con django
Pruebas unitarias con djangoPruebas unitarias con django
Pruebas unitarias con django
 
Implementation of EAV pattern for ActiveRecord models
Implementation of EAV pattern for ActiveRecord modelsImplementation of EAV pattern for ActiveRecord models
Implementation of EAV pattern for ActiveRecord models
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
 
The Ring programming language version 1.5.4 book - Part 44 of 185
The Ring programming language version 1.5.4 book - Part 44 of 185The Ring programming language version 1.5.4 book - Part 44 of 185
The Ring programming language version 1.5.4 book - Part 44 of 185
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web Framework
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Framework
 
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)
 
Guard Authentication: Powerful, Beautiful Security
Guard Authentication: Powerful, Beautiful SecurityGuard Authentication: Powerful, Beautiful Security
Guard Authentication: Powerful, Beautiful Security
 

Dernier

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 

Dernier (20)

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

Dependency injection in Scala

  • 1. Hvordan vi klarte oss uten Spring, dependency injection i Scala Alf Kristian Støyle Know IT Objectnet
  • 2. Dependency Injection Transactions
  • 3. Cake pattern ‘Cake Pattern’ because “(...) beyond my appreciation of cake, [a] cake is made of a number of layers (separated by jam), and can be sliced. The layers represent the different levels of inner class nesting. It is conceivable that you would reach the bottom layer by working your way down from the top. http://scala.sygneca.com/patterns/component-mixins
  • 4. http://lamp.epfl.ch/~odersky/papers/ScalableComponent.pdf http://jonasboner.com/2008/10/06/real-world-scala- dependency-injection-di.html
  • 5. case class User(username: String, password: String)
  • 6. class UserRepository { def authenticate(user: User): User = { println("authenticating user: " + user) user } def create(user: User): User = { println("creating user: " + user) user } }
  • 7. class UserService { val userRepository = new UserRepository def authenticate(username: String, password: String): User = userRepository.authenticate(new User(username, password)) def create(username: String, password: String): User = userRepository.create(new User(username, password)) }
  • 8. class UserRepository { def authenticate(user: User): User = { println("authenticating user: " + user) user } def create(user: User): User = { println("creating user: " + user) user } }
  • 9. trait UserRepositoryComponent { val userRepository: UserRepository class UserRepository { def authenticate(user: User): User = { println("authenticating user: " + user) user } def create(user: User): User = { println("creating user: " + user) user } } }
  • 10. class UserService { def authenticate(username: String, password: String): User = userRepository.authenticate(new User(username, password)) def create(username: String, password: String): User = userRepository.create(new User(username, password)) }
  • 11. trait UserServiceComponent extends UserRepositoryComponent { //val userRepository: UserRepository val userService: UserService class UserService { def authenticate(username: String, password: String): User = userRepository.authenticate(new User(username, password)) def create(username: String, password: String): User = userRepository.create(new User(username, password)) } }
  • 12. trait UserServiceComponent { self: UserRepositoryComponent => //val userRepository: UserRepository val userService: UserService class UserService { def authenticate(username: String, password: String): User = userRepository.authenticate(new User(username, password)) def create(username: String, password: String): User = self.userRepository.create(new User(username, password)) } }
  • 13. object ComponentRegistry extends UserServiceComponent with UserRepositoryComponent { val userRepository = new UserRepository val userService = new UserService } val userService = ComponentRegistry.userService val user = userService.authenticate("user", "password") // => User(user,password)
  • 14. import org.mockito.Mockito._ class TestingEnvironment extends UserServiceComponent with UserRepositoryComponent { val userRepository = mock(classOf[UserRepository]) val userService = new UserService } val testEnv = new TestingEnvironment when(testEnv.userRepository .authenticate(new User("user", "password"))) .thenReturn(new User("mock", "mockpwd")) val userService = testEnv.userService val user = userService.authenticate("user", "password") // => User(mock,mockpwd)
  • 15. Gotchas • Class vs Object • Typenavn
  • 16. Andre måter • Structural types • Implicit declarations • Functional currying • Spring • Guice
  • 17. Transactions import org.springframework.transaction.annotation.Transactional class UserService { @Transactional def create(username: String, password: String) = { userRepository.create(new User(username, password)) } }
  • 18. Transactions import TransactionManager._ class UserService { def create(username: String, password: String) = transactional { userRepository.create(new User(username, password)) } }
  • 19. object TransactionManager { def transactional[A](work: => A): A = ... }
  • 20. Scala DI http://jonasboner.com/2008/10/06/real-world-scala- dependency-injection-di.html http://programming-scala.labs.oreilly.com/ ch13.html#DependencyInjectionInScala http://debasishg.blogspot.com/2011/03/pushing-envelope- on-oo-and-functional.html