Discover how a simple decorator can save you from tangled, buggy code!
Why Injectable decorator in NestJS? - Purpose & Use Cases
Imagine building a large app where you have to create and manage every service and its dependencies by hand.
Every time you want to use a service inside another, you must manually create instances and pass them around.
This manual approach quickly becomes messy and error-prone.
You might accidentally create multiple instances of the same service, causing inconsistent data.
It's hard to track who needs what, and changing one service means updating many places.
The Injectable decorator in NestJS marks a class as a service that can be automatically created and shared.
It lets NestJS handle creating and providing the right instances wherever needed.
This makes your code cleaner, easier to maintain, and less buggy.
const service = new Service(); const controller = new Controller(service);
@Injectable() class Service {} @Injectable() class Controller { constructor(private readonly service: Service) {} }
It enables automatic and consistent sharing of services across your app without manual wiring.
Think of a user authentication service that many parts of your app need.
With @Injectable(), you write it once, and NestJS provides the same instance everywhere it's needed.
Manually managing service instances is hard and error-prone.
@Injectable() marks classes for automatic creation and sharing.
This leads to cleaner, more maintainable, and reliable code.