Skip to content

Instantly share code, notes, and snippets.

@privateblue
Last active December 18, 2015 02:18
Show Gist options
  • Save privateblue/5709587 to your computer and use it in GitHub Desktop.
Save privateblue/5709587 to your computer and use it in GitHub Desktop.
dependency injection pattern for factories and services
trait Driver
trait TestDriver
class PostFactory {
def hello = "post"
}
class BlogFactory {
def hello = "blog"
}
trait FactoryContainer {
val postFactory: PostFactory
val blogFactory: BlogFactory
}
trait ProductionFactoryContainer extends FactoryContainer {
val postFactory = new PostFactory with Driver
val blogFactory = new BlogFactory with Driver
}
trait TestFactoryContainer extends FactoryContainer {
val postFactory = new PostFactory with TestDriver
val blogFactory = new BlogFactory with TestDriver
}
class PostService {
this: FactoryContainer =>
def foo(implicit blogService: BlogService) = blogService.bar
def bar(implicit blogService: BlogService) = blogService.baz
}
class BlogService {
this: FactoryContainer =>
def foo(implicit postService: PostService, blogService: BlogService) = postService.bar
def bar = blogFactory.hello
def baz = postFactory.hello
}
object ProductionDIConfig {
implicit val postService = new PostService with ProductionFactoryContainer
implicit val blogService = new BlogService with ProductionFactoryContainer
}
object TestDIConfig {
implicit val postService = new PostService with TestFactoryContainer
implicit val blogService = new BlogService with TestFactoryContainer
}
object PostController {
import ProductionDIConfig._
def foo = postService.foo
def bar = postService.bar
}
object PostTest {
import TestDIConfig._
def foo = postService.foo
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment