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:

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay