Dependency Injection in Nest JS
Table of contents
What is dependency
In Nest js all providers are classes for example there are 2 classes User and Account if the User class uses the Account class to perform any action so Account class is dependency for User Class.
There are two approach to handling dependency
1) Imperative Approach
const acc = new Account()
const user = new User(acc)
pass an object of the account class in the constructor of User class.
2) Dependency Injection
This is design pattern that is based on IOC(Inversion of control).
it has multiple components
IOC container - it contains all dependency instances which can be used.
Provider - the dependency which is present in IOC container it's called Provider
Injection Token - its name of reference in the IOC container.
to register in the IOC container the Provider should be part of the module.
in Nest js, we use @Injectable decorator to tell IOC container it will act as a dependency
@Injectable()
class Account {
// write code here
}
if you want to use dependency
class User{
constructor(account: Account) {
// initialize value here
}
}