SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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 を使ってみよう
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
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
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
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
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 

Kürzlich hochgeladen (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
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...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
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...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 

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