使用awilix实现依赖注入时遇TypeError问题求助
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
UserControllerwithawilix.asClass(), Awilix keeps track of its dependencies (in this case,config). - Calling
container.resolve('userController')tells Awilix to create an instance ofUserControllerand 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

