My goal is to take charge of constructing the object and then using inversify to bind properties that are decorated with @inject
.
I initially thought I could utilize the createChild
method to bind the type to a value using either toConstantValue
or toDynamicValue
; however, it seems that neither of these methods handle property binding.
For example:
import "reflect-metadata";
import { Container, inject, injectable } from "inversify";
const container = new Container();
container.bind(Container).toConstantValue(container);
@injectable()
class Foo {
@inject(Container)
public container: Container;
}
describe("inversify", () => {
it("should inject for constructor", () => { // PASS
const c = container.createChild();
c.bind(Foo).toSelf();
const result = c.get(Foo);
expect(result.container).toBeDefined();
});
it("should inject for dynamic value", () => { // FAIL
const c = container.createChild();
c.bind(Foo).toDynamicValue(() => new Foo());
const result = c.get(Foo);
expect(result.container).toBeDefined();
});
it("should inject for constant value", () => { // FAIL
const c = container.createChild();
c.bind(Foo).toConstantValue(new Foo());
const result = c.get(Foo);
expect(result.container).toBeDefined();
});
});
Is there a straightforward way to bind properties without having to defer the object construction to the Container
?