Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Dependency Inection Tsyringe

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!

like image 662
Reculos Gerbi Neto Avatar asked May 29 '26 14:05

Reculos Gerbi Neto


1 Answers

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.

like image 97
Andrew E Avatar answered Jun 03 '26 09:06

Andrew E