In today’s fast-paced digital world, every application requires a robust notification system. Whether it’s sending an email or an SMS, the core challenge is managing multiple notification channels efficiently. So how can you handle multiple implementations (e.g., Email and SMS services) while keeping your code clean, modular, and scalable?
In this blog, we’ll dive into .NET Core’s Dependency Injection (DI) system and how it can be used to inject multiple implementations for a single interface—empowering you to send notifications via both Email and SMS effortlessly.
📧 The Challenge: Multiple Notification Channels
Imagine you’re building an application where users can opt to receive notifications via email, SMS, or both. Without proper architecture, your code might become cluttered with if-else blocks for handling each service. Instead, you can use .NET Core’s DI to keep things simple and scalable, with each service (email or SMS) implementing a single interface.
🛠 Step 1: Define the Notification Interface
To begin, define a common interface that both Email and SMS services will implement. This interface will standardize the way you send notifications, regardless of the channel.
public interface INotificationService { void SendNotification(string to, string message); }
✉️ Step 2: Create Email Notification Service
The first concrete implementation will be the Email Notification Service. This class implements the INotificationService
interface and handles sending notifications via email.
public class EmailNotificationService : INotificationService { public void SendNotification(string to, string message) { // Simulate sending an email Console.WriteLine($"Email sent to {to} with message: {message}"); } }
📱 Step 3: Create SMS Notification Service
Next, we’ll create the SMS Notification Service that implements the same INotificationService
interface but handles sending notifications via SMS.
public class SmsNotificationService : INotificationService { public void SendNotification(string to, string message) { // Simulate sending an SMS Console.WriteLine($"SMS sent to {to} with message: {message}"); } }
🌐 Step 4: Register Multiple Implementations in the DI Container
This is where the magic happens! You’ll register both EmailNotificationService
and SmsNotificationService
in the Dependency Injection (DI) container in your Startup.cs
or Program.cs
. Each implementation will be tied to the same INotificationService
interface.
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<INotificationService, EmailNotificationService>();
services.AddTransient<INotificationService, SmsNotificationService>();
services.AddControllers();
}
Note: Here we’ve used AddTransient
because notifications are typically stateless operations, but you can use AddScoped
or AddSingleton
depending on your application's needs.🔄 Step 5: Handle Multiple Implementations Using Named Services
To manage multiple implementations of a single interface, .NET Core’s DI container allows you to register services with names or keys. This way, you can inject a specific implementation at runtime based on your logic.
Let’s update the ConfigureServices
method to register the services using named options:
public void ConfigureServices(IServiceCollection services) { services.AddTransient<EmailNotificationService>(); services.AddTransient<SmsNotificationService>(); services.AddTransient<Func<string, INotificationService>>(serviceProvider => key => { switch (key) { case "Email": return serviceProvider.GetService<EmailNotificationService>(); case "SMS": return serviceProvider.GetService<SmsNotificationService>(); default: throw new ArgumentException("Invalid notification type", nameof(key)); } }); services.AddControllers(); }
Here, we’re using a factory function (Func<string, INotificationService>
) to inject the desired notification service based on a string key.
⚙️ Step 6: Inject and Use Notification Services in the Controller
Now that your services are set up, you can inject the notification factory into your controller and decide dynamically whether to use Email or SMS for notifications.
[ApiController] [Route("api/[controller]")] public class NotificationController : ControllerBase { private readonly Func<string, INotificationService> _notificationServiceFactory; public NotificationController(Func<string, INotificationService> notificationServiceFactory) { _notificationServiceFactory = notificationServiceFactory; } [HttpPost("send")] public IActionResult SendNotification(string type, string to, string message) { var notificationService = _notificationServiceFactory(type); notificationService.SendNotification(to, message); return Ok($"Notification sent via {type}."); } }In this controller, the
SendNotification
action takes the notification type (Email
or SMS
) as a parameter. Based on the type, it resolves the appropriate service using the factory and sends the notification.🚀 Testing the Notification Service
Now, you can test the service by sending requests to the API:
Send an Email:
POST /api/notification/send?type=Email&to=user@example.com&message=Hello!
{ "message": "Email sent to user@example.com with message: Hello!" }Send an SMS:
POST /api/notification/send?type=SMS&to=1234567890&message=Hello!
{ "message": "SMS sent to 1234567890 with message: Hello!" }
✨ Advantages of This Approach
- Single Interface: Both Email and SMS services implement the same
INotificationService
interface, making the system more extensible. - Loose Coupling: The controller has no direct knowledge of how notifications are sent, which improves flexibility and maintainability.
- Easy to Extend: Adding a new notification service (like push notifications or chat messages) is straightforward. Simply implement
INotificationService
and register the new service. - Dynamic Selection: Using a factory function, you can easily decide at runtime which service to use.
🚀 Wrapping It Up: Building an Extensible Notification System
By leveraging multiple implementations with a single interface in .NET Core, you can build an extensible notification system that supports multiple channels like Email and SMS. Not only does this architecture keep your code clean and modular, but it also allows for easy extensibility as your application grows.
If you need to add more notification channels (such as push notifications), all you have to do is implement the INotificationService
interface and update your DI configuration.
📝 Final Thoughts
Effective notifications are key to improving user engagement in modern applications. By using Dependency Injection to manage multiple services with a single interface, you ensure that your notification system is both flexible and scalable, ready to handle any future requirements with ease.
Let me know in the comments—what’s your preferred way of managing notifications in your applications? Have you found success with similar strategies? I'd love to hear your experiences!
This architecture ensures that you can easily expand your notification services as your application grows, keeping it flexible, testable, and scalable for the future.
Comments
Post a Comment