How would one do dependency injection in scala?

前端 未结 9 1620
鱼传尺愫
鱼传尺愫 2021-01-30 12:25

I\'m still at the beginning in learning scala in addition to java and i didn\'t get it how is one supposed to do DI there? can or should i use an existing DI library, should it

相关标签:
9条回答
  • 2021-01-30 13:08

    A new dependency injection library specifically for Scala is Dick Wall's SubCut.

    Whereas the Jonas Bonér article referenced in Dan Story's answer emphasizes compile-time bound instances and static injection (via mix-ins), SubCut is based on runtime initialization of immutable modules, and dynamic injection by querying the bound modules by type, string names, or scala.Symbol names.

    You can read more about the comparison with the Cake pattern in the GettingStarted document.

    0 讨论(0)
  • 2021-01-30 13:09

    Dependency Injection itself can be done without any tool, framework or container support. You only need to remove news from your code and move them to constructors. The one tedious part that remains is wiring the objects at "the end of the world", where containers help a lot.

    Though with Scala's 2.10 macros, you can generate the wiring code at compile-time and have auto-wiring and type-safety.

    See the Dependency Injection in Scala Guide

    0 讨论(0)
  • 2021-01-30 13:09

    I would suggest you to try distage (disclaimer: I'm the author).

    It allows you to do much more than a typical DI does and has many unique traits:

    1. distage supports multiple configurations (e.g. you may run your app with different sets of component implementations),
    2. distage allows you to correctly share dependencies across your tests and easily run same tests for different implementations of your components,
    3. distage supports roles so you may run multiple services within the same process sharing dependencies between them,
    4. distage does not depend on scala-reflect (but supports all the necessary features of Scala typesystem, like higher-kinded types).

    You may also watch our talk at Functional Scala 2019 where we've discussed and demonstrated some important capabiliteis of distage.

    0 讨论(0)
提交回复
热议问题