I'm trying to implement a cascading with tsyringe.
I have a singleton database class that has to be injected in a service class that have to be injected in a controller class:
@injectable()
class DashboardDAO implements IDashboardDAO {...}
@injectable()
class DashboardService implements IDashboardService {
construtor(@inject('DashboardDAO') private dashboardDao: IDashboardDAO){}
}
@injectable()
class DashboardController {
construtor(@inject('DashboardService') private dashboardService: IDashboardService){}
}
in my container i have the following configuration.
/** REPOSITORIES */
container.registerSingleton<IDashboardDAO>('DashboardDAO', DashboardDAO);
/** SERVICES */
container.registerSingleton<IDashboardService>('DashboardService', DashboardService);
I whould like to instantiate the controller with everything injected, something like this:
const controller = container.resolve(DashboardController);
It couldn't resolve... I'm getting the following error:
Attempted to resolve unregistered dependency token
If I do the code below works fine, but i would like to resolve the controller with all injections.
container.resolve(DashboardService);
Anyone knows why?
Tks!
The services implementing interfaces are registered correctly, though a minor improvement would be to omit the template type when registering, as it doesn't add anything:
container.registerSingleton('DashboardDAO', DashboardDAO);
container.registerSingleton('DashboardService', DashboardService);
I'd recommend using a symbol instead of a hard-coded string, but that's a minor point.
The issue is that you marked the DashboardController
class as injectable but didn't tell tsyringe
how to resolve the class. One way is to mark it as a singleton:
@singleton()
class DashboardController {...}
or:
container.registerSingleton(DashboardController)
Then resolving with container.resolve(DashboardController)
should work fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.