DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Angular dependency injection using multi-providers

When building large Angular applications, we often need to make our code scalable, maintainable, and easy to extend. Angular provides multi-providers in Dependency Injection.

Building a complex feature that needs to be highly modular, a notification system where multiple services must handle different types of notifications (emails, SMS, push notifications, etc.).

Instead of building a monolithic notification handler, we can inject various handlers dynamically without tightly coupling the system. This is where multi-providers in Angular come in handy. They allow us to inject multiple service instances that implement the same interface.

With multi-providers, we can register multiple implementations of the same service and inject them into components or other services that can work with a collection of those services. This allows for scalable, extensible architecture without breaking existing features.

Advantages:
🔸 Modular and scalable: We can easily add or remove new notification types (or any other feature) without touching the core logic of the notification manager.
🔸 Extensible: If our app grows, add another handler, and the system will automatically use it—no breaking changes needed.
🔸 Loose coupling: This pattern encourages dependency injection and the "open/closed principle" (open for extension, closed for modification).

A complete example is here: https://stackblitz.com/edit/stackblitz-starters-3eungs?file=src%2Fmain.ts


I hope you found it helpful. Thanks for reading. 🙏
Let's get connected! You can find me on:

Top comments (0)