Dependency Injection in ExpressWebJs V3
Tags: expresswebjs, typescript, express, node
Published: 2021-10-17 11:42:51

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:

![ExpressWebJs Services](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a7mc2wef8ai58c6cu4c4.jpeg)

### UserServiceInterface:
```ts
interface UserServiceInterface {
  createUser(user: object): Promise<UserObject>;
  findUserById(id: string): Promise<UserObject>;
}
export default UserServiceInterface;
```

### UserService:
```ts

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:

```ts
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:

```ts
"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](https://docs.expresswebjs.com/3.0/guide/introduction.html) for documentation and usage.

Join ExpressWebJs community on [Discord](https://discord.com/invite/vrPGZCgJuj)

You can follow ExpressWebJs on twitter [@expresswebjs](https://twitter.com/expresswebjs)

And don't forget to star ExpressWebJs Project on Github
[ExpressWebJs Javascript Version](https://github.com/Alexigbokwe/ExpressWebJs)

[ExpressWebJs Typescript Version](https://github.com/Alexigbokwe/expresswebTS-Version)