Consider the following class:
class MyClass @Inject() (ws: WSClient)(implicit executionContext: ExecutionContext)
and the code that gets this class:
app.injector.instanceOf[MyClass]
From what i understand the guice injector, injects an ExecutionContext
into that implicit ExecutionContext, but in some cases i would like to give that instance a differentExecutionContext
How am i supposed to do that.
Thanks.
You could mark an implicit parameter with annotation @Named and define a binding for the "named" ExecutionContext.
class MyClass @Inject() (ws: WSClient)
(implicit @Named("myEC") executionContext: ExecutionContext)
The binding:
package my.modules
import scala.concurrent.ExecutionContext
import com.google.inject.AbstractModule
import com.google.inject.name.Names
class MyExecutionContextModule extends AbstractModule {
override def configure(): Unit = {
bind(classOf[ExecutionContext]).annotatedWith(Names.named("myEC"))
.to(classOf[MyExecutionContextImpl])
// .toInstance(myExecutionContext)
}
}
Then you need to enable the module in Play configuration
play.modules.enabled += "my.modules.MyExecutionContextModule"
See Guice docs for more information about annotations. You can also define your own annotation or create a Module to bind implementation for your MyClass class (then it is better to make it a trait and implement it in a different class). The only Play specific thing here is that you need to enable module in config if you define one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With