Play 和 Scala 的依赖注入框架?

Depedency injection framework of Play and Scala?

我来自 spring 背景,我们在我们的项目中使用 Dependency Injections。现在我在 Play-Framework,我在 select Scala 进行开发。对于 Scala,我想使用依赖注入,我发现有很多 Dependency Injections 框架可用于 Scala。 Spring 还提供了对 Scala 依赖注入框架的支持。但我只需要 IOC 容器,所以不需要使用 spring。在 Play-Framework 文档中,他们使用 Google-Guice 作为依赖注入框架。但是我发现 SCALDI 也是一个很好的 Scala 依赖注入框架。

我仍然很困惑哪些 Dependency Injection 框架适合 ScalaPlay-Framework。还有编译时类型的安全框架可用。请建议我,选择哪个 Dependency Injection 框架?

如果您需要真正简单轻便的东西,请查看 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)
}

为了测试,只需扩展基本模块并使用 mocks/stubs 等覆盖任何依赖项,例如:

trait UserModuleForTests extends UserModule {
    override lazy val theDatabaseAccess = mockDatabaseAccess
    override lazy val theSecurityFilter = mockSecurityFilter
}

我肯定会建议 scaldi,但我也是它的创造者,所以我的意见很可能有点偏见 :D

但说真的,很难根据您的描述给出建议。我认为这取决于您正在从事的项目以及与您合作的团队。此外,您是否准备好放弃一些灵活性以支持静态类型(在这种情况下,蛋糕模式或 MacWire 将是一个不错的选择)。由于您来自 Spring 背景,我认为 scaldi 介绍的概念对您来说很熟悉。

您还需要记住,下一个版本的 Play (2.4.0) 将支持开箱即用的 DI。 Google Guice 将是默认实现(因为他们需要一些同时支持 Scala 和 Java 的库),但他们保持它非常开放,因此其他人很容易提供替代方案。很长一段时间以来,我一直致力于为新的 Play DI 机制提供 scaldi 支持,因此理想情况下,它将在 Play 2.4.0 发布时提供 first-class Scaldi - Play 2.4.0 集成.

但总的来说,我建议您尝试使用几个库,看看您最喜欢(感觉更舒服)哪个(我建议使用 scaldi、MacWire 和 cake pattern)。

最近在 scaldi 邮件列表中提出了类似的问题。也许您还会发现我的回答很有帮助:

https://groups.google.com/forum/#!topic/scaldi/TYU36h7kGqk