Dependency Injection in ExpressWebJs V3
Chukwuemeka Igbokwe
Posted on October 17, 2021
In software engineering, dependency injection is a technique in which an object receives other objects that it depends on, called dependencies.
Typically, the receiving object is called a client and the passed-in ('injected') object is called a service.
The code that passes the service to the client is called the injector. Instead of the client specifying which service it will use, the injector tells the client what service to use. The 'injection' refers to the passing of a dependency (a service) into the client that uses it.
We can inject the classes into another class’s constructor and then get the object of that class, and through that object, we can access its methods and properties.
ExpressWebJs Dependency Injection
The Service Container in ExpressWebJs is a Dependency Injection Container and a registry for the application.
ExpressWebJs Container is a powerful tool for managing dependencies and stores objects for various purposes.
First let's create our Service and register it in App/Providers/AppServiceProvider.ts register method:
UserServiceInterface:
interface UserServiceInterface {
createUser(user: object): Promise<UserObject>;
findUserById(id: string): Promise<UserObject>;
}
export default UserServiceInterface;
UserService:
import Users from "App/Model/Users_model";
import UserServiceInterface from "./UserServicerInterface";
class UserService implements UserServiceInterface {
async findUserById(id: string): Promise<object> {
return await new Promise(async (resolve, reject) => {
try {
let user = await Users.query().findById(id);
resolve(user);
} catch (error) {
reject(error);
}
});
}
async createUser(user: object): Promise<object> {
return await new Promise(async (resolve, reject) => {
try {
let result = await Users.query().insert(user);
resolve(result);
} catch (error) {
reject(error);
}
});
}
}
export default UserService;
Now we register UserService in App/Providers/AppServiceProvider.ts register method:
import ServiceProvider from "Elucidate/Support/ServiceProvider";
import UserService from "App/Service/UserService";
class AppServiceProvicer extends ServiceProvider {
/**
* Register any application services.
* @return void
*/
public register() {
this.app.singleton("UserService", UserService, "class");
}
}
We can now inject our UserService into UserController Constructor:
"use strict";
import UserServiceInterface from "App/Service/UserService/UserServicerInterface";
import { Request, Response, NextFunction } from "Elucidate/HttpContext";
import HttpResponse from "Elucidate/HttpContext/ResponseType";
class UserController {
protected userService: UserServiceInterface;
constructor(UserService: UserServiceInterface) {
this.userService = UserService;
}
/**
* Display the specified resource.
* @method GET
* @endpoint api/user/get_user/:id
* @param Request
* @return Response
*/
show = async (req: Request, res: Response, next: NextFunction) => {
try {
let user = await this.userService.findUserById(req.params.id);
return HttpResponse.OK(res, user);
} catch (error) {
return next(error);
}
};
}
export default UserController;
In this example, the UserController needs to retrieve a user by id from a data source. So, we injected our service (UserService) that is able to retrieve users.
I hope this is helpful.
Kindly visit Expresswebjs Docs for documentation and usage.
Join ExpressWebJs community on Discord
You can follow ExpressWebJs on twitter @expresswebjs
And don't forget to star ExpressWebJs Project on Github
ExpressWebJs Javascript Version
Posted on October 17, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.