typedi
typedi copied to clipboard
fix: TypeDI injects undefined in constructor parameter with cyclic dependencies
Description
When a TypeDI resolves cyclic but otherwise known parameter dependencies it will silently inject undefined in the constructor and assign the proper value to the property later after the constructor is finished.
Minimal code-snippet showcasing the problem
import "reflect-metadata";
import { Container } from "typedi";
import { UserService } from "./user.service";
import { InvoiceService } from "./invoice.service";
const instance = Container.get(UserService);
console.log(instance);
import { Service } from "typedi";
import { UserService } from "./user.service";
@Service()
export class InvoiceService {
private name: string = "InvoiceService";
constructor(private userService: UserService) {
console.log("InvoiceConstructor");
console.log(new Error("InvoiceConstructor").stack);
console.log({ userService });
}
}
import { Service } from "typedi";
import { InvoiceService } from "./invoice.service";
@Service()
export class UserService {
private name: string = "UserService";
constructor(private invoiceService: InvoiceService) {
console.log("UserServiceConstructor");
console.log(new Error("UserServiceConstructor").stack);
console.log({ invoiceService });
}
}
Logs the following:
InvoiceConstructor
<Error with stacktrace>
{userService: undefined}
UserServiceConstructor
<Error with stacktrace>
{invoiceService: {< class instance >}}
UserService {invoiceService: {…}, name: "UserService"}
Expected behavior
TypeDI should at least warn about this case or better throw an error explaining that for cyclic dependencies property injection is required.
Actual behavior
TypeDI silently injects undefined in the constructor parameter and assigns the correct value to the property after the constructor finished running.
Same problem here
Same here