Scala 使用Subcut将字符串注入第三方库
我试图将Subcut与我的项目集成以进行依赖项注入,但在将其与第三方库集成时遇到了一个问题 库需要加载文件的位置,我正在播放配置中存储该文件,并且我希望使用Subcut注入该位置。以下是我目前定义的模块:Scala 使用Subcut将字符串注入第三方库,scala,playframework,subcut,Scala,Playframework,Subcut,我试图将Subcut与我的项目集成以进行依赖项注入,但在将其与第三方库集成时遇到了一个问题 库需要加载文件的位置,我正在播放配置中存储该文件,并且我希望使用Subcut注入该位置。以下是我目前定义的模块: object ServerModule extends NewBindingModule (module => { import module._ bind[String] idBy 'location toSingle { Play.current.configuration.
object ServerModule extends NewBindingModule (module => {
import module._
bind[String] idBy 'location toSingle {
Play.current.configuration.getString("file.location").getOrElse (
throw new IllegalStateException("Cannot find location")
)
}
bind[ThirdPartyLib] toSingle {
val location = inject [String] (Some('location.toString))
ThirdPartyLib fromFile location
}
bind[Controller] toProvider { implicit module => new Controller}})
此代码可以编译,但在运行时失败,原因是找不到由“location”标识的位置字符串的绑定
还有一件事我不明白为什么我可以使用idBy'location,但使用inject[T]'location会导致编译失败?从代码看,idBy似乎只是将符号转换为字符串,然后inject方法只接受字符串。这只是Subcut API的缺陷还是我做错了什么?我发现问题在于使用符号作为绑定标识符。我使用BindingID将它们替换为一个解决方案,一切正常:
object BindingKeys {
object Location extends BindingId
}
object ServerModule extends NewBindingModule (module => {
import module._
import BindingKeys._
bind[String] idBy Location toSingle {
Play.current.configuration.getString("file.location").getOrElse (
throw new IllegalStateException("Cannot find file")
)
}
bind[ThirdPartyLib] toProvider { implicit module =>
val libLocation = inject [String] (Some(Location))
ThirdPartyLib fromFile libLocation
}
bind[Controller] toProvider { implicit module => new Controller}})