4 ms·
How do you do DI with Play? It seems as if everything is oriented towards writing static methods: - controller methods are static - DB access using the framew
by brown9-2 14y ago
How do you do DI with Play? It seems as if everything is oriented towards writing static methods:
- controller methods are static
- DB access using the framework seems to involve calling play.db.DB.getDatasource()
- Play's Cache API involves calling Cache.get(), Cache.set()
Are Play applications easy to write unit tests for? Does it involve reconfiguring the framework to use some sort of stub services rather than the real DB/Cache implementation?
- kasey_junk 14y agoIf you are asking how do you do DI with Play in java, I can't answer your question. If on the other hand you are asking for how to do it in scala, it is quite easy. Scala's language support for traits, implicit conversions, implicit parameters etc. make dependency injection trivial. Once you get used to it, things like test mocks or IOC containers seem like obvious language smells.
- brikis98 14y agoPlay actually has a really nice plugin system, which we used extensively to integrate Play at LinkedIn. The plugin system offers lightweight support for DI. For example, to use a FooPlugin, you don't use it directly, but ask Play for an instance of it: FooPlugin foo = Play.current.plugin(FooPlugin.class); foo.doSomething(); What instance you get depends on configuration (typically, a play.plugins file), which makes it easy to swap out implementations at test time. Much of Play's built-in functionality is implemented as a plugin too, including the DB code, so writing unit tests is pretty simple. There is strong support for "fake applications", integration tests, etc: http://www.playframework.com/documentation/2.1.0/ScalaTest http://www.playframework.com/documentation/2.1.0/ScalaTest We'll blog more about Play plugins in the future.
- atto 14y agoThis shows how to do dependency injection on controllers (using Guice) with Play 2.1, with a sample Play! app. The Java implementation is similar. http://eng.42go.com/play-framework-dependency-injection-guice/ http://eng.42go.com/play-framework-dependency-injection-guic... For Play! components, they don't hole you into one DI framework or another. Instead, you can use your favorite DI framework (or with Scala, the cake pattern) on top of any Play API calls.
- trailfox 14y agoUsing Guice with Play! Framework 2.1 for easy Dependency Injection: http://eng.42go.com/play-framework-dependency-injection-guice/ http://eng.42go.com/play-framework-dependency-injection-guic...
- angelohuang 14y agoHere is an example that demos how to use DI on Play. https://github.com/kouphax/play21guice https://github.com/kouphax/play21guice