Problem with dependency injection with TSyringe TypeORM Express

I am a student just starting on personal projects.

I am currently doing web-backend, and making a server using Express, TypeScript, MySQL, with typeorm and tsyringe libraries.

I am experiencing a bug that I can’t fix for hours currently 🙁

Error resolving UserController: Error: Cannot inject the dependency "userService" at position #0 of "UserController" constructor. Reason:
    Cannot inject the dependency at position #0 of "UserService" constructor. Reason:
        Attempted to resolve unregistered dependency token: "UserRepository"

So from the error, I am thinking that userService was not registered properly at the right point.

I’ve dumbed down app.ts, server.ts for debugging purposes.
I think I am doing it in the correct order (Initializing Database (ormconfig.ts) at my entry point, which as all of the dependency registration) but it keeps on telling me that the UserRepository dependency token is unregistered.

My code is as follows:

server.ts (entry point):

import app from './app';
import userRouter from './routes/user.router';
import { initializeDatabase } from './config/ormconfig';

const PORT = process.env.PORT || 3000;

initializeDatabase().then(() => {
    app.use('/api/user', userRouter);

    app.get('/', (req, res) => {
        res.send('Hello World');
    });

    app.listen(PORT, () => {
        console.log(`Server is running on port ${PORT}`);
    });
}).catch((error) => {
    console.error('Error starting the server:', error);
});

app.ts:

import 'reflect-metadata';
import express from 'express';
import bodyParser from 'body-parser';

const app = express();
app.use(bodyParser.json());

export default app;

user.router.ts:

import { Router } from 'express';
import { container } from 'tsyringe';
import { UserController } from '../controllers/user.controller';

const router = Router();
try {
    const userController = container.resolve(UserController);
    console.log('usercontroller successfully resolved', userController);

    router.post('/register', userController.createUser.bind(userController));
    router.post('/login', userController.loginUser.bind(userController));
    router.get('/:user_key', userController.getUserByKey.bind(userController));
    router.get('/', userController.getAllUsers.bind(userController));
} catch (error) {
    console.error('Error resolving UserController:', error);
}
export default router;

user.controller.ts:

import { Request, Response } from 'express';
import { injectable, inject } from 'tsyringe';
import { UserService } from '../services/user.service';

@injectable()
export class UserController {
    constructor(
        private userService: UserService
    ) { }
// methods 

user.service.ts:

import { Repository } from 'typeorm';
import { Address } from '../entities/address.entity';
import { UserService } from './user.service';
import { injectable, inject } from 'tsyringe';

@injectable()
export class AddressService {
    constructor(
        @inject('UserService') private userService: UserService,
        @inject('AddressRepository') private addressRepository: Repository<Address>
    ) { }
// methods

ormconfig.ts

import 'reflect-metadata';
import { DataSource } from 'typeorm';
import dotenv from 'dotenv';
import { container } from 'tsyringe';
import { REPOSITORY_TOKENS } from './constants';

import { User } from '../entities/user.entity';

import { UserService } from '../services/user.service';

dotenv.config({ path: '.env' });

const { DB_DATABASE, DB_USER, DB_HOST, DB_PASSWORD } = process.env;

if (!DB_DATABASE || !DB_USER || !DB_HOST || !DB_PASSWORD) {
    throw new Error('Missing database configuration environment variables.');
}

export const AppDataSource = new DataSource({
    type: 'mysql',
    host: DB_HOST,
    port: 3306,
    username: DB_USER,
    password: DB_PASSWORD,
    database: DB_DATABASE,
    synchronize: false,
    logging: false,
    entities: [User, Address, Routine, Item, SkinAttribute, ItemOrder, OrderDetail, Review],
});


export const initializeDatabase = async () => {
    try {
        await AppDataSource.initialize();
        console.log('Database connection established successfully');

        const repositories = [
            { name: 'UserRepository', entity: User },
            // other entities
        ];

        for (const repo of repositories) {
            container.register(repo.name, { useValue: AppDataSource.getRepository(repo.entity) });
        }

        container.register(UserService, { useClass: UserService });
        // other services

    } catch (error) {
        console.error('Error initializing database:', error);
    }
}

If anyone could help me out and give me some tips or ideas, that would be great!

To remove any typos in the names of the repositories, i’ve made a separate constants.ts file to fill in, for no luck.

Most of my changes I’ve already applied in the code above, but got the same error.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật