通过DIP在Swift中进行依赖注入:如何处理相同类型但不同值的解析

时间:2019-07-17 14:42:30

标签: ios swift design-patterns dependency-injection

我通过DIP深入了Swift中的依赖注入,遇到了一些我不知道如何正确避免的冲突。我的内部类型相同,但值不同,但是DIP当然会解析最后一个已注册的类型。我将用代码向您解释: 这是ViewController和ViewModel 1

final class ViewController1: UIViewController {

  @IBOutlet weak var label: UILabel!
  var viewModel: ViewModelA!

  override func viewDidLoad() {
    super.viewDidLoad()
    self.label.text = viewModel.value
  }

}

struct ViewModelA {
  typealias UseCases = ProtocolA
  let value: String

  init(useCases: UseCases) {
    self.value = useCases.value
  }
}

第二个ViewController和ViewModel相同,只是名称不同。 ViewController2和ViewModelB。 Composition1是

enum Composition1 {
  static func configure(_ container: DependencyContainer) {
    container.register {
      Data(value: "Composition1")
    }

    // Use Cases
    container.register { (data: Data) in
      data as ViewModelA.UseCases
    }

    // View Models
    container.register { useCases in
      ViewModelA(useCases: useCases)
    }

    // View Controller
    container
      .register(storyboardType: ViewController1.self, tag: "ViewController1")
      .resolvingProperties { container, controller in
        controller.viewModel = try container.resolve()
    }

    DependencyContainer.uiContainers.append(container)
  }
}

“ Composition2”是

enum Composition2 {
  static func configure(_ container: DependencyContainer) {
    container.register {
      Data(value: "Composition2")
    }

    // Use Cases
    container.register { (data: Data) in
      data as ViewModelB.UseCases
    }

    // View Models
    container.register { useCases in
      ViewModelB(useCases: useCases)
    }

    // View Controller
    container
      .register(storyboardType: ViewController2.self, tag: "ViewController2")
      .resolvingProperties { container, controller in
        controller.viewModel = try container.resolve()
    }

    DependencyContainer.uiContainers.append(container)
  }
}

RootComposition是:

enum RootComposition {
  static func configure() -> DependencyContainer {
    let container = DependencyContainer()
    Composition1.configure(container)
    Composition2.configure(container)
    return container
  }
}

因此,所有ViewController-1和2在标签中均显示“ Composition2”,因为Composition2.configure称为最后一个。 有人可以帮我吗?注册和重置容器的正确方法是什么?

0 个答案:

没有答案