Skip to content

Issue with injection on typeorm repository to service . #250

@Abolfazl-MI

Description

@Abolfazl-MI

Hello .
I'm trying to inject typeorm repository to my service layer to use it but I got this error, I have searched google and used AI to solve but no solution workd. also I have found question in stack over flow but no answer was there

question link:
https://stackoverflow.com/questions/78959606/problem-with-dependency-injection-with-tsyringe-typeorm-express

my container code :

container.register<number>("PORT", {
  useValue: parseInt(process.env.PORT || "3000"),
});
container.register<DataSource>("DataSource", { useValue: AppDataSource });
container.register<Application>(Application, { useClass: Application });
container.register<Repository<WeatherEntity>>("weatherEntityRepo", {
  useValue: AppDataSource.getRepository(WeatherEntity),
});
container.register<WeatherService>(WeatherService, {
  useClass: WeatherService,
});
container.register<WeatherController>(WeatherController, {
  useClass: WeatherController,
});

my service code :

@injectable()
export class WeatherService {
  

  constructor(@inject('weatherRepository') private readonly weatherRepository: Repository<WeatherEntity>) {
   
  }

  async findAll(limit?: number, offset?: number): Promise<WeatherEntity[]> {
    return await this.weatherRepository.find({
      take: limit,
      skip: offset,
    });
  }
}

and my controller

@injectable()
export class WeatherController {
  constructor(
    @inject(WeatherService) private readonly weatherService: WeatherService
  ) {}

  async getAllWeathers(
    request: Request,
    response: Response,
    next: NextFunction
  ) {
    try {
      const weathers: WeatherEntity[] = await this.weatherService.findAll();
      response.status(200).json({
        statusCode: response.statusCode,
        message: "success",
        data: [weathers],
      });
      return;
    } catch (error) {
      next(error);
      return;
    }
  }
}

and routes

export const weatherRouter: Router = Router();
const weatherController = container.resolve(WeatherController);

/**@GET get all weathers */
weatherRouter.get("/", weatherController.getAllWeathers);

/**@GET  get single weather*/
weatherRouter.route("/:id").get((request: Request, response: Response) => {
  response.status(200).json({
    statusCode: response.statusCode,
    message: "success",
    data: {
      title: "single weather object here",
    },
  });
  return;
});

your support appreciated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions