Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an implicit value to an instance thats retrieved by guice

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.

like image 954
Gleeb Avatar asked May 09 '16 15:05

Gleeb


1 Answers

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.

like image 174
yahor Avatar answered Sep 18 '22 08:09

yahor