Reputation: 83
I'm new to Scala and I'm trying to figure out the best approach for dependency injection. I have Java background and I used to use both Guice and Spring IoC.
I used to use a provider class with the @Provider annotation to chose implementation or use beans.xml in Spring and just use the @Inject annotation (or in Spring, @Autowired) to inject instances of a class into my services.
In Scala, I read about the cake pattern but it seems rather complicated to me. All I want to achieve is what I already have in Java: get a singleton of an interface type with specific implementation.
My question is whether using Scala object type would be sufficient.
Example:
trait TestDI { }
class Impl1 extends TestDI { }
class Impl2 extends TestDI { }
object TestDI extends Impl1 { }
So I'd just use TestDI in my service which would actually use the implementation of Impl1. So my initial interface (trait) and the singleton object would have the same name.
Upvotes: 1
Views: 1124
Reputation: 16412
I think either Macwire or Scaldi matches Guice style quite closely. I like Macwire because it's standard Scala based framework based on macros, no other magical sauce is used (like byte manipulation).
Other ways to do DI are described in my answer here:
Scala - write unit tests for objects/singletons that extends a trait/class with DB connection
Upvotes: 1