InversifyJS icon indicating copy to clipboard operation
InversifyJS copied to clipboard

lazyInject decorator not working with RequestScope

Open allardmuis opened this issue 5 years ago • 6 comments

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 avatar Mar 26 '19 15:03 allardmuis

~~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 avatar Mar 29 '19 07:03 allardmuis

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.

allardmuis avatar Apr 02 '19 15:04 allardmuis

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

Luka4ever avatar Feb 11 '20 22:02 Luka4ever

I'm also facing this issue

Wgil avatar Sep 09 '20 21:09 Wgil

+1

liangyuqi avatar Jun 20 '21 10:06 liangyuqi

@allardmuis, can you share your code?

fabiohvp avatar Jul 11 '21 01:07 fabiohvp