3

I am migrating my application to Play 2.5 and I have the following issue:

import play.modules.reactivemongo.ReactiveMongoApi

trait Foo {
  override def reactiveMongoApi: ReactiveMongoApi = current.injector.instanceOf[ReactiveMongoApi]
  ...
}
object Foo extends Foo

As current is now deprecated, I would like to replace it. However, I can't use @Inject() (val reactiveMongoApi: ReactiveMongoApi) as I am in a Trait. How am I supposed to do it ?

Scipion
  • 11,449
  • 19
  • 74
  • 139

1 Answers1

3

You can do something like this:

import play.modules.reactivemongo.ReactiveMongoApi

trait Foo {
  def reactiveMongoApi: ReactiveMongoApi

  // other methods
}

@Singleton
class FooClass @Inject()(reactiveMongoApi: ReactiveMongoApi) extends Foo {
    // other methods
}

Notice how the property name in FooClass (reactiveMongoApi) matches the method defined at the trait Foo. After that, you can declare a module to provide the correct bindings.

marcospereira
  • 12,045
  • 3
  • 46
  • 52
  • Something still confuses me, how do you create the instance of FooClass afterwards ? – Scipion Apr 27 '16 at 06:08
  • Guice will handle that for you. After you [create and configure a module](https://www.playframework.com/documentation/2.5.x/ScalaDependencyInjection#Programmatic-bindings), it is up to the DI framework to create **and** inject the required dependencies. Also, see this answer http://stackoverflow.com/a/35823086/4600 – marcospereira Apr 27 '16 at 16:46