Classes exported under the same name and aliased are confused as the same token by the dependency injection mechanism
See original GitHub issueBug Report
Input Code
Consider the following minimal project:
// provider1.ts
export class Token {};
// provider2.ts
export class Token {};
// main.module.ts
import {Module} from "@nestjs/common";
import {Token as Token1} from "./provider1";
import {Token as Token2} from "./provider2";
@Module({
providers: [
Token1,
Token2,
{
provide: 'foo',
useFactory: (injectedToken1, injectedToken2) => {
console.warn(Token1 === Token2); // false, expected
console.warn(injectedToken1 === injectedToken2); // true, unexpected
console.warn(injectedToken1 instanceof Token2); // true, unexpected
console.warn(injectedToken2 instanceof Token2); // true, expected
},
inject: [
Token1,
Token2
]
}
]
})
export class MainModule {}
Here, provider1.ts
and provider2.ts
both export a class under the same name - Token
. When imported by the module, they are aliased respectively to Token1
and Token2
. These aliases are then used as provider keys.
When both tokens are injected into the foo
provider factory, both arguments of the factory are strictly equals: they are both the same instance of Token2
. It means that the dependency injection mechanism instanciate a singleton from Token2
and then assign this singleton to both the tokens Token1
and Token2
.
Expected behavior
Token1
and Token2
are different classes. They are different tokens and are not equal, nor loosely, neither strictly.
It is expected that they are not confused by the dependency injection mechanism of Nest.
Possible Solution
None.
And this is a big issue because there is no way for a developer to control how a class is exported by a module the application depends on. When two different modules export the same class, it becomes impossible to alias them and use these aliases as provider keys.
Note that this also impacts functions used as factory.
Environment
Nest version: 7.6.17
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (3 by maintainers)
This has been fixed in v8 https://github.com/nestjs/nest/pull/6349 (which I’m hoping to release within ~1 month).
@kamilmysliwiec
👍
Amazing, thanks a lot!