【问题标题】:Combining Dependency Injections and inheritance with Play 2.5将依赖注入和继承与 Play 2.5 相结合
【发布时间】:2016-04-28 06:19:36
【问题描述】:

在将应用程序从 2.4 迁移到 2.5(并摆脱所有静态引用)的过程中,我做了以下事情:

class Generic @Inject()(implicit val mat: Materializer, cache: CacheApi, wsClient: WSClient, configuration: play.api.Configuration) 
{ ... }

@Singleton
class Concrete1 @Inject() (gw:Generic) { ... }

@Singleton
class Concrete2 @Inject() (gw:Generic) { ... }

要使用它,我会使用 Generic 实例注入 Concrete1/2。 它有效,但在网上看到其他几个关于此的示例后,它似乎不太正确。

我正在考虑这样修改它:

    abstract class Generic(cache: CacheApi, wsClient: WSClient, configuration: play.api.Configuration) 
    { ... }

    @Singleton
    class Concrete1(cache: CacheApi, wsClient: WSClient, configuration: play.api.Configuration) 
       extends Generic(cache, wsClient, configuration) { ... }

    @Singleton
    class Concrete2(cache: CacheApi, wsClient: WSClient, configuration: play.api.Configuration) 
       extends Generic(cache, wsClient, configuration) { ... }

那么为了能够做到:@Inject() (c1:Concrete1, c2:Concrete2) 我想我需要它们成为由 https://www.playframework.com/documentation/2.5.x/ScalaDependencyInjection#Programmatic-bindings 定义的模块? 在这里做什么更有意义?

【问题讨论】:

    标签: scala playframework playframework-2.5


    【解决方案1】:

    我实际上不同意你的“看起来不太正确”的说法。

    我认为您的第一个示例更接近地反映了 组合优于继承 哲学,该哲学已成为 accepted as a more maintainable way 构建软件。

    在不了解您的 ConcreteGeneric 类的情况下,很难说更多,但如果后者基于继承的结构更容易正确的单元测试,而模拟 Generic 并将其注入以测试 Concrete 类将是微不足道的。

    其他好处:

    • 减少噪音/重复声明
    • 与 Play 框架的关联较少(无需模块定义)
    • 未来的灵活性(当您的具体类共享第二个“通用”类时)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      • 2021-04-16
      相关资源
      最近更新 更多