This content originally appeared on DEV Community and was authored by Nhan Nguyen
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:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
- Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs
This content originally appeared on DEV Community and was authored by Nhan Nguyen
Nhan Nguyen | Sciencx (2024-09-18T02:45:50+00:00) Angular dependency injection using multi-providers. Retrieved from https://www.scien.cx/2024/09/18/angular-dependency-injection-using-multi-providers/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.