Dependency Injection
Dependency Injection is the technique of supplying a dependent object, such as a module or component, with a dependency like a service, thereby injecting it into the component’s constructor. An example of this taken from the sequelize chapter is below. Here we are injecting the UserRespository
service into the constructor of the UserService
, thereby providing access to the User Database repository from inside the UserService
component.
@
Injectable
()
export
class
UserService
implements
IUserService
{
constructor
(
@
Inject
(
'UserRepository'
)
private
readonly
UserRepository
:typeof
User
)
{
}
...
}
In turn this UsersService
will be injected into the UsersController in the src/users/users.controller.ts
file, which will provide access to the UsersService
from the routes that point to this controller. More about Routes and Dependency injection in later chapters.