SlideShare a Scribd company logo
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

More Related Content

What's hot

Dependency Injection in Functional Programming
Dependency Injection in Functional ProgrammingDependency Injection in Functional Programming
Dependency Injection in Functional Programming
Duana Stanley
 
Rails GUI Development with Ext JS
Rails GUI Development with Ext JSRails GUI Development with Ext JS
Rails GUI Development with Ext JS
Martin Rehfeld
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
Gil Fink
 
Visual Studio.Net - Sql Server
Visual Studio.Net - Sql ServerVisual Studio.Net - Sql Server
Visual Studio.Net - Sql Server
Darwin Durand
 
えっ、なにそれこわい
えっ、なにそれこわいえっ、なにそれこわい
えっ、なにそれこわい
Kei Shiratsuchi
 
Controle de estado
Controle de estadoControle de estado
Controle de estado
Bruno Bilescky
 
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 Apps
Kris 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 utfordringene
Stian Danenbarger
 
Matters of State
Matters of StateMatters of State
Matters of State
Kris Wallsmith
 
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
Colin O'Dell
 
Grails UI Primer
Grails UI PrimerGrails UI Primer
Grails UI Primer
Matthew Taylor
 
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-london
Kris Wallsmith
 
Windows ストアーアプリで SQLite を使ってみよう
Windows ストアーアプリで SQLite を使ってみようWindows ストアーアプリで SQLite を使ってみよう
Windows ストアーアプリで SQLite を使ってみよう
ShinichiAoyagi
 

What's hot (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 を使ってみよう
 

Viewers also liked

Learning Lisp
Learning LispLearning Lisp
Learning Lisp
Alf Kristian Støyle
 
Barriere secu
Barriere secuBarriere secu
Barriere secu
Farid Sellabi
 
Cultures:Foreign and Domestic
Cultures:Foreign and DomesticCultures:Foreign and Domestic
Cultures:Foreign and Domestic
Kdemaio
 
Cultures:Foreign and Domestic
Cultures:Foreign and DomesticCultures:Foreign and Domestic
Cultures:Foreign and Domestic
Kdemaio
 
Simple machines scavenger hunt
Simple machines scavenger huntSimple machines scavenger hunt
Simple machines scavenger hunt
danbel2
 
Clojure workshop
Clojure workshopClojure workshop
Clojure workshop
Alf Kristian Støyle
 
Bakerfinal
BakerfinalBakerfinal
Bakerfinalbakedizz
 
Karma profile
Karma profileKarma profile
Karma profile
Manmeet Singh
 
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...
Instytut Ekonomiki Miast i Regionów
 
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
Instytut Ekonomiki Miast i Regionów
 
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.)
Instytut 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 powerpoint
danbel2
 
Sobre a cultura e a personalidade.
Sobre a cultura e a personalidade.Sobre a cultura e a personalidade.
Sobre a cultura e a personalidade.
Filosofía Luis IES Otero Pedrayo Ourense
 

Viewers also liked (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
 

Similar to Dependency injection in Scala

Dependency injection in Scala
Dependency injection in ScalaDependency injection in Scala
Dependency injection in Scala
Knoldus 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 Classes
Cody 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 js
Francois 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, Macoscope
Macoscope
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
Rafael Winterhalter
 
Pruebas unitarias con django
Pruebas unitarias con djangoPruebas unitarias con django
Pruebas unitarias con django
Tomá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 models
Kostyantyn Stepanyuk
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage
 
Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
Marco Otte-Witte
 
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
Mahmoud Samir Fayed
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Frameworkvhazrati
 
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
IndicThreads
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
Xebia IT Architects
 
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 Security
Ryan Weaver
 

Similar to 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
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based 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
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of 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
 

Recently uploaded

GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 

Recently uploaded (20)

GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 

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