3 ms·
That seems too dogmatic. Does the fact that Foo has a static function that knows how to create its dependencies disqualify the class from being a case of DI?
by loevborg 1y ago
That seems too dogmatic. Does the fact that Foo has a static function that knows how to create its dependencies disqualify the class from being a case of DI?
class Foo {
private nowFn: () => Date;
constructor(nowFn: () => Date) {
this.nowFn = nowFn;
}
doSomething() {
console.log(this.nowFn());
}
static create(opts: { nowFn?: () => Date } = {}) {
return new Foo(opts.nowFn ?? (() => new Date()));
}
}
- physPop 1y agoYes because injecting nowFn is trivial and not a case for DI. Consider a database handle, or network socket, or http response payload. Clearly each class shouldn't be making its own version of those.
- cyanydeez 1y agoYou're nitpicking for no good reason. You can create global handles to each of those items, and let them instantiate with the class or override them with a create function. Dependency injection boils down the question of whether or not you can dynamically change a dependency at runtime.
- loevborg 1y agoYou're right, stateful dependencies like DB handles need to be passed in manually, and that's a bit of extra legwork you need to do.
- Charon77 1y agoJust use a static variable to the DB instance / pool, maybe using singletons, so everyone needing it have access.