Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lazyInject decorator not working with RequestScope #1073

Open
allardmuis opened this issue Mar 26, 2019 · 6 comments
Open

lazyInject decorator not working with RequestScope #1073

allardmuis opened this issue Mar 26, 2019 · 6 comments

Comments

@allardmuis
Copy link

allardmuis commented Mar 26, 2019

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
Copy link
Author

allardmuis commented Mar 29, 2019

Duplicate of #678
After taking a better look it appears that issue 678 refers to different decorators, so not a duplicate after all.

@allardmuis
Copy link
Author

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
Copy link

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

@Wgil
Copy link

Wgil commented Sep 9, 2020

I'm also facing this issue

@liangyuqi
Copy link

+1

@fabiohvp
Copy link

@allardmuis, can you share your code?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants