microsoft / tsyringe

Lightweight dependency injection container for JavaScript/TypeScript
MIT License
5.19k stars 172 forks source link

Is there a way to auto bind `this` on all classes resolved by the container? #186

Closed ylc395 closed 2 years ago

ylc395 commented 3 years ago

This is a common pattern in code base:

const {method1, method2} = container.resolve(SomeService);

However, method1/method2 has wrong this when calling them.

BamboOSZ commented 2 years ago

Have this same issue. Have to manually bind on every root resolve. Any chance for a fix/alternative solution to this?

nmsobri commented 2 years ago

the best way is to use arrow function instead since it has lexical scoping

megastels commented 2 years ago

doing this

const {method1, method2} = container.resolve(SomeService);

is the same as

const {method1, method2} = new SomeService();

container shouldn't bind methods

if you really need bind methods, you can use something like this https://www.npmjs.com/package/autobind-decorator or use arrow functions