inversify / InversifyJS

A powerful and lightweight inversion of control container for JavaScript & Node.js apps powered by TypeScript.
http://inversify.io/
MIT License
11.33k stars 719 forks source link

lazyInject decorator not working with RequestScope #1073

Open allardmuis opened 5 years ago

allardmuis commented 5 years ago

The lazyInject decorator appears to be a replacement for the constructor-injection. But the scoping rules don't work with lazy injection.

Expected Behavior

The 'lazyInject' decorator should inject the same instance when the binding is done in RequestScope.

Current Behavior

See this example code for an illustration:

import { Container, injectable } from 'inversify';
import getDecorators from 'inversify-inject-decorators';
import 'reflect-metadata';

const container = new Container();
const { lazyInject } = getDecorators(container);

@injectable()
class A {
    public id: number;
    constructor() {
        this.id = Math.floor(Math.random() * 1000);
    }
}
container.bind(A).to(A).inRequestScope();

@injectable()
class B {
    constructor(
        public a1: A,
        public a2: A
    ) { }
}
container.bind(B).to(B);
const b = container.get(B);
console.log(b.a1.id === b.a2.id); // expecting true, actual true

@injectable()
class C {
    @lazyInject(A) public a1: A;
    @lazyInject(A) public a2: A;
}
container.bind(C).to(C);
const c = container.get(C);
console.log(c.a1.id === c.a2.id); // expecting true, actual false

The problem is that the lazyInject decorator uses container.get itself, creating a new request scope for every resolution.

allardmuis commented 5 years ago

Duplicate of https://github.com/inversify/InversifyJS/issues/678 After taking a better look it appears that issue 678 refers to different decorators, so not a duplicate after all.

allardmuis commented 5 years ago

I have it working with my own decorator instead of the decorator from inversify-inject-decorators. It is not ready for a pull request yet, for example because it doesn't support Named and Tagged services yet. Let me know of you are interested.

Luka4ever commented 4 years ago

@allardmuis I'm currently facing this same problem, can I get you to share the work you've done on this issue?

Wgil commented 4 years ago

I'm also facing this issue

liangyuqi commented 3 years ago

+1

fabiohvp commented 3 years ago

@allardmuis, can you share your code?