处理依赖注入

Handling dependency injections

假设我有以下代码:

import (
   handlerA "some/path/handlerA"
   handlerB "some/path/handlerB"
   handlerC "some/path/handlerC"
   handlerD "some/path/handlerD"
   ....
   handlerZ "some/path/handlerZ"
)

func DoSomething(a handlerA.A, b handlerB.B, c handlerC.C, d handlerD.D..., z handlerZ.Z) {
   a.DoA()
   b.DoB()
   c.DoC()
   d.DoD()
   ....
   z.DoZ()
}

我显然使函数 DoSomething(...) 可模拟,因为这使我的函数单元可测试。但是正因为如此,我的函数需要注入所有依赖项,所以我得到了很多参数。

Golang 有没有更好的方法来处理很多依赖?

处理多次注入的一种方法是使用结构作为包装器:

type SomethingDoer struct {
  a handlerA.A,
  b handlerB.B,
  c handlerC.C,
  d handlerD.D,
  ...
  z handlerZ.Z,
}

func (sd SomethingDoer) DoSomething() {
   sd.a.DoA()
   sd.b.DoB()
   sd.c.DoC()
   sd.d.DoD()
   ....
   sd.z.DoZ()
}

我自己又看了一遍这个问题才弄明白的...