Appearance
Dependency Injection (DI)
Dependency injection is a software design pattern in which one or more dependencies (or services) are injected, or passed by reference, into a dependent object. By doing this, we can replace a dependency without changing any code and it also reduces the boilerplate code in our business logic.
Advantage of using DI
Decoupling
Dependency injection makes your modules less coupled resulting in a more maintainable codebase.
Easier unit testing
Instead of using hardcoded dependencies you can pass them into the module you would like to use.
Faster development
With dependency injection, after the interfaces are defined it is easy to work without any merge conflicts.
Awilix IOC Container
In this CMS we are using Awilix as an IOC container to resolve all the dependencies.
Resolving Dependencies In Constructor
class AppUserService extends BaseService {
constructor(opts) {
super(apiUsers);
this.activityLogs = opts.activityLogsService;
}In the above snippet, the AppUserService class is resolving the activityLogsService instance's reference in the contructor by using the (opts) which is the awilix cradle which was setup while booting up the application.
Resolving directly from Container
const { container } = require("@container");
const adminController = container.resolve('adminController');
router.get('/', [checkPermission('user-management.admins.view')], adminController.index);We can also resolve the dependencies directly by importing the container setup during applcation bootup.
These two methods are popularly used in this CMS for resolving the dependencies. As there as more ways of resolving, storing and instantiating the Awilix Container. Know More About Awilix