Custom Providers in Nest Js | Arshnoor Singh

Custom Providers in Nest Js

Custom providers in nest JS consist of dependency injection.

Dependency injection is an inversion of control (IoC) technique wherein you delegate instantiation of dependencies to the IoC container, instead of doing it in your own code imperatively.

Standard providers

The providers property takes an array of providers. So far, we've supplied those providers via a list of class names. In fact, the syntax providers: [UsersService] is short-hand for the more complete syntax.

Now that we see this explicit construction, we can understand the registration process. Here, we are clearly associating the token UsersService with the class UsersService. The short-hand notation is merely a convenience to simplify the most common use-case where the token is used to request an instance of a class by the same name.

Custom providers

What happens when our requirements go beyond those offered by Standard providers? Here are a few examples:

  1. We want to create a custom instance instead of having Nest instantiate (or return a cached instance of) a class.
  2. We want to re-use an existing class in a second dependency.
  3. We want to override a class with a mock version for testing.

Value providers: useValue

The useValue syntax is useful for injecting a constant value, putting an external library into the Nest container or replacing a real implementation with a mock object.