typedi icon indicating copy to clipboard operation
typedi copied to clipboard

fix: TypeDI injects undefined in constructor parameter with cyclic dependencies

Open NoNameProvided opened this issue 4 years ago • 2 comments

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"}

Stackblitz

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.

NoNameProvided avatar Feb 14 '21 12:02 NoNameProvided

Same problem here

ghost avatar May 12 '21 01:05 ghost

Same here

theophane-girard avatar Sep 30 '21 09:09 theophane-girard