Nest js Tutorial Series — Part 3: Providers, Services & Dependency Injection

Kaushik Samanta
2 min readJul 16, 2019

--

https://nestjs.com/

Nest is heavily inspired by the Angular framework. The fundamental concepts are the same in both frameworks. Similar to angular providers you can use it to inject dependencies in controllers and other providers. Nest classes which can be treated as a provider are services, repositories, factories, helpers, etc. In order to create a provider simply annotated the class with @Injectable decorator.

app.service.ts

Typically a controller should only handle the HTTP requests and should delegate all complex tasks (DB query, Calling another API etc. ) to the services.

Provider Registration

app.module.ts

Dependency Injection

According to Wikipedia —

Dependency injection is a technique whereby one object supplies the dependencies of another object. A “dependency” is an object that can be used, for example a service. Instead of a client specifying which service it will use, something tells the client what service to use. The “injection” refers to the passing of a dependency (a service) into the object (a client) that would use it.

Here the framework creates the instance for you when you add the service to the provider. Then you can access the service through the constructor. Below snippet shows how to use dependency injection.

book.controller.ts

When the Nest application is bootstrapped, every dependency is resolved, and a singleton instance of every provider is created. And, when the application shuts down, each provider is destroyed.

If you enjoyed this tutorial, please click the 👏 button and share to help others find it! Feel free to leave a comment below.

Next part — Modules and Middlewares.

--

--

Kaushik Samanta

Polyglot Developer — Working on multiple languages and frameworks. Experience in building scalable, maintainable and reliable codebases.