typedi
typedi copied to clipboard
question: receiving ServiceNotFoundError after trying basic example from documentation
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?

Your official document also doesn't work.
Same problem here
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.
Your official document also doesn't work.
This issue has been open for 2 years