Last active
March 25, 2023 12:26
-
-
Save loicdescotte/ce278a6783c1b293ce2c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PrintService { | |
def print = println("I'm a real service") | |
} | |
trait Services { | |
val printService = new PrintService() | |
// put your other services here | |
} | |
//for example, a Play controller | |
class App (deps: Services) /*extends Controller*/ { | |
import deps._ | |
def run = printService.print | |
} | |
// In Scala singletons (objects) can be parameterized, so no need for DI framework or container | |
object DependenciesModule extends Services //global object for your app or controller | |
object ServicesApp extends App(DependenciesModule) | |
ServicesApp.run //services | |
//testing | |
val printServiceMock = new PrintService { //or use Mockito | |
override def print = println("I'm a mock") | |
} | |
object MockServices extends Services { | |
override val printService = printServiceMock | |
} | |
object FakeServicesApp extends App(MockServices) | |
FakeServicesApp.run // "I'm a mock" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment