How to use MediatR Notifications email

Sep 11 2023

 
 

Many thanks to the sponsors who make it possible for this newsletter to be free for readers.

 

Today's issue is sponsored by Packt

 

Create, deploy, and scale production-grade microservices-based applications effortlessly. Dive into the world of Spring Boot 3, Java 17, and Spring Cloud 2022 with this updated guide.
Explore Spring's AOT module, observability, distributed tracing, and Helm 3 for Kubernetes packaging.
Begin with Docker Compose, advance to Kubernetes with Istio, and delve into resilience, reactivity, and API documentation with OpenAPI.
Discover Netflix Eureka, Spring Cloud Gateway, Prometheus, Grafana, and the EFK stack for monitoring.

 
 

Background

 
 

 

It is often used in CQRS (Command Query Responsibility Segregation) architectures but is not limited to such applications. Essentially, you create simple C# classes for your commands and queries, and then create handler classes that handle those commands and queries. You can then use MediatR to dispatch these requests to their respective handlers.

 

MediatR also brings implementations of other patterns.
With MediatR, it is possible to implement a notification system.

 

Let's see how to implement MediatR Notifications feature in ASP.NET Core using C#.

 
 

Example

 
 

Let's say that you have a system for alarming certain services, such as the police station, firefighters and emergency services, in case of an alarm or an accident.

 

You need to implement the publish-subscriber connection , so that every time an accident happens, all parties are notified and can react.

 

In that case, you will send an object that contains all the necessary information about the accident, for example, the location.

 

Let's create that class:

public class AccidentNotificaiton : INotification
{
    public AccisdentNotification(string location)
    {
        Location = location;
    }

    public string Location { get; }
}

 

AccidentNotification implements the INotification interface that comes from the MediatR namespace and thus allows you to create a notification that will move through the system.

 
 

Notification Handlers

 
 

Who will receive that notification?

 

Well, all those who register receive it - more precisely, every service that will be interested in that notification. They represent subscribers .

 

Here's how you can implement a subscriber, more precisely a notification handler:

public class PoliceSubscriber : INotificationHandler<AccidentNotification>
{
    public async Task Handle(AccidentNotification notification,
                             CancellationToken cancellationToken)
    {
        Console.WriteLine();
        Console.WriteLine($"The police service received a notificaiton about the accident");
        Console.WriteLine($"Police were dispatched to the location: {notification.Location}");
    }
}
INotificationHandler is an interface also from the MediatR namespace that accepts the notification type, in this case, I want the police station to accept accident notifications.

 

Only one Handle method is implemented, with notification and cancellation token parameters. This is identical to the IRequest implementation method (the one we use in CQRS).

 

In the end, the subscriber performs his part of the work, in this case, I print on the console what happens next.

 

In this way, you can add as many handlers as you need. Who else needs to know that an accident has happened?

 
 

Publish Notification

 
 

When such an accident occurs, it is necessary to inform all parties. More precisely, it is necessary for the publisher to send a notification to all subscribers.

 

How can you do that?

 

Well, very simple.

[HttpPost("notify-accident")]
public async Task<IActionResult> NotifyAboutAccident(AccidentNotification notification)
{
    await _mediator.Publish(notification);

    return Ok();
}
As with IRequest when we call .Send() over MediatR, here I call the Publish method with the passed notification.

 

MediatR will look at all handlers that handle that type of notification and send them a notification.

 
 

Services Configuration

 
 

You just need to register MediatR using the following call:

builder.Services
       .AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));

 
 

Result:

 
 
Result

And that's it.

 
 

Wrapping up

 
 

In today's Newsletter issue, I showed you how to implement MediatR Notification in ASP.NET Core.

 

On the example, I showed you that it is necessary to implement the type of notification that we want to exchange, the handlers that receive and handle the notification (subscribers), and how to publish the notification (publisher).

 

You can check Sending MediatR Notifications in Parallel.

 

You can go to the project's GitHub repository and get acquainted with the details.

 

That's all from me today.

Join 10,950+ subscribers to improve your .NET Knowledge.

There are 3 ways I can help you:

Design Patterns Simplified ebook

Go-to resource for understanding the core concepts of design patterns without the overwhelming complexity. In this concise and affordable ebook, I've distilled the essence of design patterns into an easy-to-digest format. It is a Beginner level. Check out it here.


Sponsorship

Promote yourself to 10,950+ subscribers by sponsoring this newsletter.


Join .NET Pro Weekly Newsletter

Every Monday morning, I share 1 actionable tip on C#, .NET & Arcitecture topic, that you can use right away.


Subscribe to
.NET Pro Weekly

Subscribe to the .NET Pro Weekly and be among the 10,950+ subscribers gaining practical tips and resources to enhance your .NET expertise.