DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

2

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:

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay