MediatR Guide + sample (#2218)

* Add guide for MediatR

* Add sample for MediatR

* Fix exposed token in program.cs

* Fix review points

* Remove newline in MediatrDiscordEventListener.cs
This commit is contained in:
Duke
2022-04-05 19:18:25 +02:00
committed by GitHub
parent d8757a5afa
commit 53ab9f3b16
15 changed files with 354 additions and 0 deletions

View File

@@ -0,0 +1 @@
.AddMediatR(typeof(Bot))

View File

@@ -0,0 +1,16 @@
// MessageReceivedNotification.cs
using Discord.WebSocket;
using MediatR;
namespace MediatRSample.Notifications;
public class MessageReceivedNotification : INotification
{
public MessageReceivedNotification(SocketMessage message)
{
Message = message ?? throw new ArgumentNullException(nameof(message));
}
public SocketMessage Message { get; }
}

View File

@@ -0,0 +1,46 @@
// DiscordEventListener.cs
using Discord.WebSocket;
using MediatR;
using MediatRSample.Notifications;
using Microsoft.Extensions.DependencyInjection;
using System.Threading;
using System.Threading.Tasks;
namespace MediatRSample;
public class DiscordEventListener
{
private readonly CancellationToken _cancellationToken;
private readonly DiscordSocketClient _client;
private readonly IServiceScopeFactory _serviceScope;
public DiscordEventListener(DiscordSocketClient client, IServiceScopeFactory serviceScope)
{
_client = client;
_serviceScope = serviceScope;
_cancellationToken = new CancellationTokenSource().Token;
}
private IMediator Mediator
{
get
{
var scope = _serviceScope.CreateScope();
return scope.ServiceProvider.GetRequiredService<IMediator>();
}
}
public async Task StartAsync()
{
_client.MessageReceived += OnMessageReceivedAsync;
await Task.CompletedTask;
}
private Task OnMessageReceivedAsync(SocketMessage arg)
{
return Mediator.Publish(new MessageReceivedNotification(arg), _cancellationToken);
}
}

View File

@@ -0,0 +1,17 @@
// MessageReceivedHandler.cs
using System;
using MediatR;
using MediatRSample.Notifications;
namespace MediatRSample;
public class MessageReceivedHandler : INotificationHandler<MessageReceivedNotification>
{
public async Task Handle(MessageReceivedNotification notification, CancellationToken cancellationToken)
{
Console.WriteLine($"MediatR works! (Received a message by {notification.Message.Author.Username})");
// Your implementation
}
}

View File

@@ -0,0 +1,4 @@
// Program.cs
var listener = services.GetRequiredService<DiscordEventListener>();
await listener.StartAsync();