我在弄清楚如何处理使用 typescript 制作的 rest web 服务上的依赖项和注入时遇到了麻烦。我试图避免根据依赖倒置原则依赖于我的域类的反转。这是到目前为止的项目结构:
core/ (domain classes)
expressjs/ (web service context)
inversify/ (the injection magic for my domain classes should happen here)
other-modules/ (concrete interface implementations on 3rd party techs)
这是关于我的课程的示例:
interface DomainInterface {
foo(): void;
}
interface DomainService {
bar();
}
class ConcreteClass implements DomainInterface {
constructor(colaborator: DomainService) { }
foo() {
this.colaborator.bar();
...
}
}
现在我想通过 inversify 注入所有依赖项,但我不想修改我的所有域类以通过 @injectable 装饰器使它们可注入。
我虽然做的一件事是做一个包含 @injectable 依赖于 inversify 模块的类,该模块继承了我需要注入的每个域类。例如:
@injectable()
class InverisfyConcreteClass extends ConcreteClass {
constructor(@inject(DomainService) colaborator: DomainService) {
super(colaborator);
}
}
但这导致我遇到一个问题,即我有很多域类,并且创建这么多类会很疯狂。
另一种方法是创建一个“上下文”类,其中包含对所有类的引用,将它们绑定到容器并在需要时检索它们:
class InversifyInjectionContext {
container: Container;
bind() {
// bind all needed instances somehow (??)
}
concreteClass() {
return container.get<ConcreteClass>();
}
concreteDomainService() {
return container.get<AnyConcreteDomainService>();
}
}
现在的问题是我不知道如何创建实例并在 inversify 容器中正确注册它们,所以我可以在应用程序之后检索它们。
解决这个问题的最佳方法是什么?