Building a Better MediatR Publisher with Channels (and Why You Shouldn’t)

Listen to this Post

In this article, Milan Jovanović explores the limitations of MediatR’s default notification system and demonstrates how to create a custom ChannelPublisher implementation. He also covers configuration, distributed tracing, and important considerations before implementation.

Key Points:

  • Limitations of MediatR’s default notification system.
  • Creating a custom ChannelPublisher implementation.
  • Configuring it with just one line of code.
  • Distributed tracing for comparing approaches.
  • Important gotchas and considerations before implementing.

Practical Code Example:

Here’s a sample implementation of a custom ChannelPublisher in .NET:

public class ChannelPublisher : INotificationHandler<INotification>
{
private readonly Channel<INotification> _channel;

public ChannelPublisher()
{
_channel = Channel.CreateUnbounded<INotification>();
}

public async Task Handle(INotification notification, CancellationToken cancellationToken)
{
await _channel.Writer.WriteAsync(notification, cancellationToken);
}

public IAsyncEnumerable<INotification> ReadAllAsync(CancellationToken cancellationToken)
{
return _channel.Reader.ReadAllAsync(cancellationToken);
}
}

**Configuration Example:**

services.AddSingleton<ChannelPublisher>();
services.AddMediatR(typeof(Startup));

**Distributed Tracing Command (Linux):**

To trace system calls and signals, use the `strace` command:

strace -p <process_id> -o output.txt

**What Undercode Say**

The article provides a deep dive into improving MediatR’s notification system using channels, highlighting both the benefits and potential pitfalls. While the custom implementation offers async notification processing, it’s crucial to weigh the complexity and performance trade-offs.

For distributed tracing, tools like `strace` in Linux or `dotnet-trace` in .NET can be invaluable. On Windows, you can use `PerfView` for similar insights. Additionally, consider using `htop` or `top` in Linux to monitor system resources during high-load scenarios.

For further reading on .NET architecture and performance optimization, check out Microsoft’s official documentation. If you’re working with Linux, mastering commands like netstat, lsof, and `tcpdump` can significantly enhance your debugging and monitoring capabilities.

In conclusion, while the custom ChannelPublisher implementation offers a powerful alternative to MediatR’s default system, it’s essential to thoroughly test and profile your application to ensure it meets your performance and scalability requirements. Always consider the trade-offs and explore additional tools and commands to optimize your workflow.

References:

Hackers Feeds, Undercode AIFeatured Image