How to pass an implicit value to an instance thats retrieved by guice
Asked Answered
H

1

5

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.

Heartbreak answered 9/5, 2016 at 15:15 Comment(4)
I think you're mixing up two separated things: dependency injection (via guice - inside Play) and implicit parameters. In this specific case you're injecting ws while declaring a class that has one implicit parameter. See playframework.com/documentation/2.5.x/…Shangrila
Ok so how do i pass a value to that classes implicit parameterHeartbreak
You may want to read more about Scala implicit parameters. Here's a link (but you can find plenty) daily-scala.blogspot.it/2010/04/implicit-parameters.htmlShangrila
I guess there's more here than meets the eye. It seems like Play provides an implicit ExecutionContext to any guice-injected instance, though I can't still find where this behaviour is implemented or documented.Rant
B
7

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.

Bloodcurdling answered 9/5, 2016 at 17:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.