0

I have been following component based strucutre for my projects and I have clone the repo for this purpose listed here

Everything is fine and testable except services.

So I decided to use awilix to inject dependencies in services.

This is what I tried.

I created a container.js file in the loaders.

const awilix = require('awilix');

const db = require('../db');
const AuthService = require('../components/auth/auth.service');

const container = awilix.createContainer({
  injectionMode: awilix.InjectionMode.PROXY,
});

function setup() {
  container.register({
    db: awilix.asValue(db),
    doGetAllService: awilix.asValue(AuthService.doRegister),
  });
}

module.exports = {
  container,
  setup,
};

I invoked this container in app.js as below.

const express = require('express');

const app = express();

const cors = require('cors');

// load environment config variables
require('dotenv').config();
require('./loaders/container').setup();
...

In the doc it says, the first argument will be injected dependencies. But when I do console.log I still get undefined.

const doRegister = async (opts, { username, password }) => {
  console.log(opts);
  const user = await User.create({
    username,
    password,
    role_id: 1, // assign role id here
  });
   return user;
};

For entire folder structure and source conde please go through the repo.

confusedWarrior
  • 938
  • 2
  • 14
  • 30
  • In your repository I dont see any awilix references, nor do I see how you register the awilix cradle to your http server (f.e. awilix-express). Without this you will never get anything injected. Was this your intention with posting this question? In any case I hope my answer below helps you with your problem. – David Zwart Oct 07 '21 at 16:03

1 Answers1

1

In order to have awilix resolve any dependencies something must consume from or bootstrap the dependency container. One way is container.resolve(...); (not permanent) and another is by binding the cradle to the request pipeline.

For awilix-express one can bind the cradle to requests like scopePerRequest(container):

Add this to your server middleware

app.use(scopePerRequest(container));

In case you are in need of a complete source, you can check this repository: https://github.com/fdm-monster/fdm-monster/blob/fb0fc8075cfcd840ae7b50519fe6dd1525b03034/server/app-core.js#L63

I recommend you take a look at awilix-express for a complete server setup with controllers as this truly is cleaner than just function based API routes: https://www.npmjs.com/package/awilix-express

David Zwart
  • 431
  • 5
  • 23