How can I perform partial properties injection using Inversify?
Imagine we have a class like this:
class MyClass {
constructor(
@inject(EXTERNAL_A) private externalA: ExternalClassA,
private b: string
) {}
}
Is there a way to utilize MyClass with inversify in other classes if all the possible values of b are known at compile time? Essentially, I only need instances of MyClass with b = "a"
and b = "b"
.
The solution I have come across so far involves defining two different bindings or using a factory to directly instantiate new MyClass
.
In the first scenario, I would need to do something like this:
container.bind<MyClass>(CLASS_A).toConstantValue(
new MyClass(container.get<ExternalClassA>(EXTERNAL_A), "a")
);
container.bind<MyClass>(CLASS_B).toConstantValue(
new MyClass(container.get<ExternalClassA>(EXTERNAL_A), "b")
);
This approach seems messy and does not address the issue of constructing deep object hierarchies manually.
What is the optimal solution here?
An advanced challenge would be if it's possible to resolve dependency trees by replacing the same single dependency with a provided one. For example, consider:
|-----B-----e
A|-----C-----e
|-----D
|-----e
I want to replace the e
dependency with my custom one. How can this be achieved?