Skip to main content

Notification System: Implementing Multiple Services with a Single Interface in .NET Core

 

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

Popular posts from this blog

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...

.NET 10: Your Ultimate Guide to the Coolest New Features (with Real-World Goodies!)

 Hey .NET warriors! 🤓 Are you ready to explore the latest and greatest features that .NET 10 and C# 14 bring to the table? Whether you're a seasoned developer or just starting out, this guide will show you how .NET 10 makes your apps faster, safer, and more productive — with real-world examples to boot! So grab your coffee ☕️ and let’s dive into the awesome . 💪 1️⃣ JIT Compiler Superpowers — Lightning-Fast Apps .NET 10 is all about speed . The Just-In-Time (JIT) compiler has been turbocharged with: Stack Allocation for Small Arrays 🗂️ Think fewer heap allocations, less garbage collection, and blazing-fast performance . Better Code Layout 🔥 Hot code paths are now smarter, meaning faster method calls and fewer CPU cache misses. 💡 Why you care: Your APIs, desktop apps, and services now respond quicker — giving users a snappy experience . 2️⃣ Say Hello to C# 14 — More Power in Your Syntax .NET 10 ships with C# 14 , and it’s packed with developer goodies: Field-Bac...