tsyringe icon indicating copy to clipboard operation
tsyringe copied to clipboard

Issue with injection on typeorm repository to service .

Open Abolfazl-MI opened this issue 1 year ago • 2 comments

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.

Abolfazl-MI avatar Jan 07 '25 06:01 Abolfazl-MI

just replace this complicated library with this simple implementation using npm inject.min

you just need import Inject and use it outside constructor. no need to register try!

@Abolfazl-MI

service

import { Inject } from 'inject.min';

export class WeatherService {
  @Inject(Repository<WeatherEntity>) private readonly weatherRepository!: Repository<WeatherEntity>

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

controller

import { Inject } from 'inject.min';
import { WeatherService } from '../services/weather.service';
import { Request, Response, NextFunction } from 'express';

export class WeatherController {
  @Inject(WeatherService) private readonly weatherService!: WeatherService

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

nenjack avatar Jan 15 '25 18:01 nenjack

@Abolfazl-MI tell me how it worked https://www.npmjs.com/package/inject.min

nenjack avatar Jan 15 '25 18:01 nenjack