inversify / InversifyJS

A powerful and lightweight inversion of control container for JavaScript & Node.js apps powered by TypeScript.
http://inversify.io/
MIT License
11.24k stars 713 forks source link

Usage Question: Inversifyjs injection of mongoose model inferred as anonymous function at runtime #1239

Open patb23 opened 4 years ago

patb23 commented 4 years ago

I referred mongoose sample to build an express application with mongoose. Pasting the relevant section for brevity. I placed console.log in the constructor and in the findById. The model is correctly inferred at the time of binding but from within the findById, it is inferred as anonymous function because of which getting ' this.Model.findById is not a functio' error.

@injectable()
export class GenericRepository<Entity,  TModel extends Document> implements Repository<Entity> {

    protected Model: Model<TModel>;
    constructor(@inject(TYPES.DbClient) dbClient: mongoose.Mongoose,
                @unmanaged() name: string, @unmanaged() schemaDefinition: SchemaDefinition) {
        const schema = new Schema(schemaDefinition, { collection: name});
        this.Model = dbClient.model<TModel>(name,  schema);
        console.log(this.Model);
    }

    async findById(id: string): Promise<Entity> {
        console.log(this.Model);
        return new Promise((resolve, reject) => {

screenshot from the debuggere screenshot when invoking findById. As can be seen, this.Model is 'anonymous'. Need help in understanding this behavior

patb23 commented 4 years ago

Found the reason - seems inversifyTracer is causing the issue. If I comment the following lines, I am able to use the mongoose model. Need help to understand the reason

        const tracer = new InversifyTracer({filters: ["*:*", "!Mongo*", "!EventEmitter"],});

        tracer.on('call', (callInfo: CallInfo) => {
            console.log(`${callInfo.className} ${callInfo.methodName} `);
        });

        tracer.on('return', (returnInfo: ReturnInfo) => {
            console.log(`${returnInfo.className} ${returnInfo.methodName} returned ${returnInfo.result} - ${returnInfo.executionTime}ms`);
        });

        tracer.apply(container);