You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用awilix实现依赖注入时遇TypeError问题求助

Fixing "Cannot read property 'config' of undefined" in Awilix Dependency Injection

Hey there! I see exactly what's causing that error in your Awilix setup. Let's break it down and fix it step by step.

The Root Cause

The problem is that you're manually instantiating UserController with new UserController() instead of letting Awilix handle the instance creation through the container. When you do this, the constructor's { config } parameter is undefined—since you didn't pass anything to it—hence the TypeError you're seeing.

Awilix only injects dependencies when you retrieve instances from the container using container.resolve(), not when you create them with new yourself.

Fixed Code

Here's the corrected version of your code with the key change highlighted:

const awilix = require("awilix");
const config = {
 server: "8.8.8.8",
};
class UserController {
 constructor({ config }) {
 this.config = config;
 }
}
const container = awilix.createContainer({
 injectionMode: awilix.InjectionMode.PROXY,
});
container.register({
 config: awilix.asValue(config),
 userController: awilix.asClass(UserController),
});
function setup() {
 // ✅ Retrieve the instance from the container instead of using new
 const user = container.resolve('userController');
 console.log(user.config); // Will log { server: "8.8.8.8" }
}
module.exports = { container, setup };

Key Explanation

  • When you register UserController with awilix.asClass(), Awilix keeps track of its dependencies (in this case, config).
  • Calling container.resolve('userController') tells Awilix to create an instance of UserController and automatically inject all required dependencies into its constructor.
  • If you use new UserController(), you're bypassing Awilix's injection mechanism entirely, so the constructor gets no arguments, leading to your error.

Testing the Fix

Run your code after making this change, and you should see the config object logged correctly without any errors.

内容的提问来源于stack exchange,提问作者Ben Jonson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:28:32