我来自春天的背景,我们在项目中使用Dependency Injections
。现在我在Play-Framework
,我选择Scala进行开发。使用Scala我想使用依赖注入,我发现有很多Dependency Injections
框架可供Scala使用。 Spring还提供对Scala依赖注入框架的支持。但我只需要IOC容器,所以不需要使用弹簧。在Play-Framework
文档中,他们使用Google-Guice for Dependency注入框架。但我发现SCALDI
也是Scala的一个很好的依赖注入框架。
我仍然困惑哪些Dependency Injection
框架适合Scala
和Play-Framework
。还有编译时类型安全框架可用。请建议我,去哪个Dependency Injection
框架?
答案 0 :(得分:2)
如果你需要一些非常简单和轻量级的东西,请看一下Macwire:https://github.com/adamw/macwire
使用示例:
class DatabaseAccess()
class SecurityFilter()
class UserFinder(databaseAccess: DatabaseAccess, securityFilter: SecurityFilter)
class UserStatusReader(userFinder: UserFinder)
trait UserModule {
import com.softwaremill.macwire._
lazy val theDatabaseAccess = wire[DatabaseAccess]
lazy val theSecurityFilter = wire[SecurityFilter]
lazy val theUserFinder = wire[UserFinder]
lazy val theUserStatusReader = wire[UserStatusReader]
}
将生成
trait UserModule {
lazy val theDatabaseAccess = new DatabaseAccess()
lazy val theSecurityFilter = new SecurityFilter()
lazy val theUserFinder = new UserFinder(theDatabaseAccess, theSecurityFilter)
lazy val theUserStatusReader = new UserStatusReader(theUserFinder)
}
对于测试,只需扩展基本模块并覆盖与模拟/存根等的任何依赖关系,例如:
trait UserModuleForTests extends UserModule {
override lazy val theDatabaseAccess = mockDatabaseAccess
override lazy val theSecurityFilter = mockSecurityFilter
}
答案 1 :(得分:2)
我肯定会建议scaldi,但我也是它的创造者,所以我的观点很可能有点偏颇:D
但严重的是,很难对你的描述提出建议。我认为这取决于您正在进行的项目以及您正在与之合作的团队。此外,您是否准备好放弃一些支持静态类型的灵活性(在这种情况下,蛋糕模式或MacWire将是一个不错的选择)。由于您来自Spring背景,我认为scaldi引入的概念对您来说很熟悉。
您还需要记住,Play(2.4.0)的下一个版本将支持DI开箱即用。 Google Guice将是默认实现(因为它们需要一些支持Scala和Java的库),但是它们保持开放,因此其他人提供替代方案非常容易。很长一段时间以来,我一直致力于为新的Play DI机制提供scaldi支持,因此理想情况下,它将在Play 2.4.0发布时提供,以提供一流的Scaldi-Play 2.4.0集成。 / p>
但总的来说,我建议你尝试几个库,看看你最喜欢哪个(感觉更舒服)(我建议使用scaldi,MacWire和蛋糕模式)。
最近在scaldi邮件列表中提出了类似的问题。也许你会发现我的答案有帮助: