[英]Multiple Dependency Inection Tsyringe
I'm trying to implement a cascading with tsyringe.我正在尝试使用 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.问题是您将
DashboardController
类标记为可注入,但没有告诉tsyringe
如何解析该类。 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.然后使用
container.resolve(DashboardController)
解析应该可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.