typedi icon indicating copy to clipboard operation
typedi copied to clipboard

question: receiving ServiceNotFoundError after trying basic example from documentation

Open alanlee8421 opened this issue 3 years ago • 3 comments

const AlanService = require('../../services/alan/alan.service');
const Container = require('typedi').Container;

exports.readAll = async (req, res, next) => {
  try {
    const alanService = Container.get(AlanService);
    const result = await alanService.alan();
    responseJson(req, res, result);
  } catch (error) {
    console.error(error);
    errorHandler(req, res, error, next);
  }
};

error log:

ServiceNotFoundError: Service with "MaybeConstructable<AlanService>" identifier was not found in the container. Register it before usage via explicitly calling the "Container.set" function or using the "@Service()" decorator.

This error occurs after version 0.8.0.

Your guide explains that when a service is used as above, it checks for the existence of an instance and creates or retrieves it when .get is called. And the above code worked normally until 0.8.0. Can you explain how the usage has changed from the next version?

스크린샷 2021-04-01 오후 12 36 09

Your official document also doesn't work.

alanlee8421 avatar Apr 01 '21 05:04 alanlee8421

Same problem here

artur-dani avatar Apr 07 '21 18:04 artur-dani

Sorry, documentation needs an update. In the past, we did attempt to blindly construct anything you request but that was not a good solution. Now you have to register everything first before requesting it from the container.

If the old solution is required for you you can write a miniam abstraction, something like this:

import { ContainedType, ContainerInterface } from 'typeorm';
import { Container, Constructable } from 'typedi';

export class TypeDIContainerProvider implements ContainerInterface {
  get<T>(constructable: ContainedType<T>) {
    /**
     * TypeDI only resolves values for registered types, so we need to register
     * them before to requesting them from the default container.
     */
    if (!Container.has(constructable as Constructable<T>)) {
      Container.set({ id: constructable, type: constructable as Constructable<T> });
    }

    return Container.get(constructable as Constructable<T>);
  }
}

I will leave this issue open until documentation is fixed.

NoNameProvided avatar Jan 14 '22 07:01 NoNameProvided

Your official document also doesn't work.

This issue has been open for 2 years

chrono-jeff avatar May 30 '23 14:05 chrono-jeff