skip to Main Content

When I give the logger as a dependency to the class I am getting the following error:

Screenshot of error message details

E:my_sitesrccommondatabaseMongoDBConnector.ts:11
constructor(@inject(COMMON_TYPES.Logger) logger: ILogger) {
^TypeError: Cannot read properties of undefined (reading 'Logger')
at Object.<anonymous> (E:my_sitesrccommondatabaseMongoDBConnector.ts:11:38)
at Module._compile (node:internal/modules/cjs/loader:1469:14)
at Module.m._compile (E:my_sitenode_modulests-nodesrcindex.ts:1618:23)
at Module._extensions..js (node:internal/modules/cjs/loader:1548:10)
at Object.require.extensions.<computed> [as .ts] (E:my_sitenode_modulests-nodesrcindex.ts:1621:12)
at Module.load (node:internal/modules/cjs/loader:1288:32)
at Function.Module._load (node:internal/modules/cjs/loader:1104:12)
at Module.require (node:internal/modules/cjs/loader:1311:19)
at require (node:internal/modules/helpers:179:18)
at Object.<anonymous> (E:my_sitesrccommoncommon_injection_container.ts:4:1)

this is inversify.config.ts

import { Container, ContainerModule } from 'inversify';
import { commonContainer, COMMON_TYPES } from '../common_injection_container';
import { ILogger } from '../../common/interfaces/ILogger';

const appContainer = new Container();

appContainer.load(commonContainer);

const logger = appContainer.get<ILogger>(COMMON_TYPES.Logger);

interface ContainerDefinition {
    container: ContainerModule;
    name: string;
}

const containers: ContainerDefinition[] = [
];

containers.forEach(({ container, name }) => {
    try {
        appContainer.load(container);
        logger.info(`${name} container loaded successfully`);
    } catch (error) {
        logger.error(`Failed to load ${name} container`);
        if (error instanceof Error) {
            logger.trackError(error);
        } else {
            logger.error('An unknown error occurred while loading the container.');
        }
    }
});

export { appContainer };

this is common_injection_container.ts

import { ContainerModule, interfaces } from 'inversify';
import { ILogger } from './interfaces/ILogger';
import Logger from './utils/Logger';
import { MongoDBConnector } from './database/MongoDBConnector';


const COMMON_TYPES = {
    Logger: Symbol.for('Logger'), 
    MongoDBConnector: Symbol.for('MongoDBConnector'), 


};

const commonContainer = new ContainerModule((bind: interfaces.Bind) => {
    bind<ILogger>(COMMON_TYPES.Logger).to(Logger).inSingletonScope();

    bind<MongoDBConnector>(COMMON_TYPES.MongoDBConnector).to(MongoDBConnector);


});

export { commonContainer, COMMON_TYPES };

this is MongoDBConnector.ts

import mongoose from 'mongoose';
import { inject, injectable } from 'inversify';
import { ILogger } from '../../common/interfaces/ILogger';
import { COMMON_TYPES } from '../../common/common_injection_container';

@injectable()
export class MongoDBConnector {
    private logger: ILogger;

    constructor(@inject(COMMON_TYPES.Logger) logger: ILogger) {
        if (!logger) {
            throw new Error('Logger not found during MongoDBConnector injection');
        }
        this.logger = logger;
    }

    public async connectToMongoDB(): Promise<void> {
        try {
            await mongoose.connect(process.env.MONGODB_URI!, {
                serverSelectionTimeoutMS: 30000, 
            });
            this.logger.info('Connected to MongoDB'); 
        } catch (error: any) {
            if (error instanceof Error) {
                this.logger.error('Could not connect to MongoDB'); 
                this.logger.error(`Error details: ${error.message}`); 
            } else {
                this.logger.error('Could not connect to MongoDB with an unknown error');
            }
            throw error; 
        }
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    I tried everything I could but it didn't work! First of all, thank you for your answer and guidance! I uploaded the codes on GitHub! If you can check my codes and tell me where the problem is! I'm going crazy!!! I want to use Logger as DI in the whole project! This code I uploaded is a small part of my project so that I can find the problem! I used the same method in all classes and that's why I get the same error message in all classes https://github.com/farhadesmaeili/my_site


  2. The problem might be because of the hoisting that happens when defining a class.

    It looks to me that classes and functions declarations are hoisted first (ahead of everything else). This means that the import will be evaluated after the class is defined (although uninitialized).

    For example, if your code is like this:

    import { something } from 'path/to/file';
    class type extends something {}
    

    Then it will be evaluated like this:

    class type extends something {} // something is a promised value
    import { something } from 'path/to/file'; // changes something value
    

    It is possible to change the order of the class definition by placing the class in a variable, like this:

    export const MongoDBConnector = class MongoDBConnector {
      // ...
    };
    

    Maybe just changing this will work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search