简体   繁体   English

创建一个 AbstractModule 来为 3rd 方库注入依赖项

[英]Creating a AbstractModule to inject a dependency for a 3rd party library

I have a 3rd party library that I am trying to inject the configuration into the constructor.我有一个 3rd 方库,我试图将配置注入到构造函数中。 This is what I need to do:这是我需要做的:

class MyModule(configuration: Configuration) extends AbstractModule {
  override def configure(): Unit = {
     bind(classOf[TwitterApi])
       .to(classOf[MyTwitterApi])
       .asEagerSingleton
  }
}

The constructor of MyTwitterApi doesn't take a Play.api.Configuration but a typesafe.config.Config MyTwitterApi 的构造函数不采用 Play.api.Configuration 而是采用 typesafe.config.Config

class MyTwitterApi(config: Config) ...

So I need to do pass configuration.underlying to my constructor, how is this possible using DI in this AbstractModule?所以我需要将configuration.underlying传递给我的构造函数,这怎么可能在这个 AbstractModule 中使用 DI?

I need this instance to be a singleton also.我也需要这个实例成为单身人士。

You can use provider to setup your module with eagerSingleton您可以使用提供程序通过eagerSingleton 设置您的模块

import com.google.inject.{AbstractModule, Provider}

class MyModule(configuration: Configuration) extends AbstractModule {
  override def configure(): Unit = {
     val twitterApiProvider: Provider[TwitterApi] = 
       () => new MyTwitterApi(configuration.underlying)
     bind(classOf[TwitterApi])
       .toProvider(twitterApiProvider)
       .asEagerSingleton
  }
}

You can find a working example with sample classes at - https://scastie.scala-lang.org/sarveshseri/ujwvJJNnTpiWDqdkBJQoFw/2您可以在https://scastie.scala-lang.org/sarveshseri/ujwvJJNnTpiWDqdkBJQoFw/2找到一个包含示例类的工作示例

I think you want something like this:我想你想要这样的东西:

class MyModule(configuration: Configuration) extends AbstractModule {
  override def configure(): Unit = {
     val myTwitterApiInstance = new MyTwitterApi(configuration.underlying)
     bind(classOf[TwitterApi])
       .toInstance(myTwitterApiInstance)
  }
}

Or another approach would be to provide a binding for Config but if your MyTwitterApi doesn't have @Inject annotation this won't help.或者另一种方法是为Config提供绑定,但如果您的MyTwitterApi没有@Inject注释,这将无济于事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM