Skip to content

Commit 78c2306

Browse files
committed
Added MediatorPattern example
1 parent c5cb39a commit 78c2306

13 files changed

+238
-0
lines changed

MediatorPattern/ColorConsole.cs

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
namespace MediatorPattern;
2+
3+
public static class ColorConsole
4+
{
5+
public static void WriteLineCommandHandler(string print) => WriteLineColored(print, ConsoleColor.Blue);
6+
public static void WriteLineQueryHandler(string print) => WriteLineColored(print, ConsoleColor.Yellow);
7+
public static void WriteLineProgram(string print) => WriteLineColored(print, ConsoleColor.Green);
8+
public static void WriteLineRepository(string print) => WriteLineColored(print, ConsoleColor.DarkMagenta);
9+
10+
private static void WriteLineColored(string toPrint, ConsoleColor color)
11+
{
12+
Console.ForegroundColor = color;
13+
Console.WriteLine(toPrint);
14+
Console.ResetColor();
15+
}
16+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
using MediatR;
2+
3+
namespace MediatorPattern.Command;
4+
5+
public class AddNewUserCommand : IRequest<User>
6+
{
7+
public string Name { get; set; }
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
using MediatorPattern.Infrastructure;
2+
using MediatR;
3+
4+
namespace MediatorPattern.Command;
5+
6+
public class AddNewUserCommandHandler : IRequestHandler<AddNewUserCommand, User>
7+
{
8+
private readonly UserRepository _userRepository;
9+
10+
public AddNewUserCommandHandler(UserRepository userRepository)
11+
{
12+
_userRepository = userRepository;
13+
}
14+
15+
public Task<User> Handle(AddNewUserCommand request, CancellationToken cancellationToken)
16+
{
17+
ColorConsole.WriteLineCommandHandler($"Passing user '{request.Name}' to repository");
18+
var user = new User { Name = request.Name };
19+
var userFromRepo = _userRepository.AddUser(user);
20+
ColorConsole.WriteLineCommandHandler($"Saved user to repository and return result");
21+
return Task.FromResult(userFromRepo);
22+
}
23+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
using MediatR;
2+
3+
namespace MediatorPattern.Command;
4+
5+
public class DeleteAllUsersCommand : IRequest<Unit>
6+
{
7+
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
using MediatorPattern.Infrastructure;
2+
using MediatR;
3+
4+
namespace MediatorPattern.Command;
5+
6+
public class DeleteAllUsersCommandHandler : IRequestHandler<DeleteAllUsersCommand, Unit>
7+
{
8+
private readonly UserRepository _userRepository;
9+
10+
public DeleteAllUsersCommandHandler(UserRepository userRepository)
11+
{
12+
_userRepository = userRepository;
13+
}
14+
15+
public Task<Unit> Handle(DeleteAllUsersCommand request, CancellationToken cancellationToken)
16+
{
17+
ColorConsole.WriteLineCommandHandler($"Deleting all users");
18+
_userRepository.DeleteAll();
19+
ColorConsole.WriteLineCommandHandler($"All users deleted");
20+
return Task.FromResult(Unit.Value);
21+
}
22+
}

MediatorPattern/Domain/User.cs

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
namespace MediatorPattern;
2+
3+
public class User
4+
{
5+
public int Id { get; set; }
6+
7+
public string Name { get; set; }
8+
}

MediatorPattern/Execution.cs

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
using MediatorPattern.Command;
2+
using MediatorPattern.Query;
3+
using MediatR;
4+
5+
namespace MediatorPattern;
6+
7+
public class Execution
8+
{
9+
private readonly IMediator _mediator;
10+
11+
public Execution(IMediator mediator)
12+
{
13+
_mediator = mediator;
14+
}
15+
16+
public async Task RunAsync()
17+
{
18+
ColorConsole.WriteLineProgram("Creating a new user with name 'Steven'");
19+
var user = await _mediator.Send(new AddNewUserCommand { Name = "Steven" });
20+
ColorConsole.WriteLineProgram($"User has id: {user.Id}");
21+
22+
Console.WriteLine();
23+
24+
ColorConsole.WriteLineProgram($"Get count of users with name 'Rebecca'");
25+
var count = await _mediator.Send(new GetUserCountQuery { NameFilter = "Rebecca" });
26+
ColorConsole.WriteLineProgram($"Found {count} entries");
27+
28+
Console.WriteLine();
29+
30+
ColorConsole.WriteLineProgram($"Deleting all users");
31+
await _mediator.Send(new DeleteAllUsersCommand());
32+
ColorConsole.WriteLineProgram($"All users deleted");
33+
34+
}
35+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
namespace MediatorPattern.Infrastructure;
2+
3+
public class UserRepository
4+
{
5+
private readonly List<User> _users = new();
6+
7+
public User AddUser(User user)
8+
{
9+
ColorConsole.WriteLineRepository($"Adding user with name: '{user.Name}'");
10+
var currentMaxId = !_users.Any() ? 0 : _users.Max(u => u.Id);
11+
user.Id = currentMaxId + 1;
12+
_users.Add(user);
13+
14+
return user;
15+
}
16+
17+
public int GetUserCount(string? name)
18+
{
19+
ColorConsole.WriteLineRepository($"Filtering users where name is '{name}'");
20+
return name == null ? _users.Count : _users.Count(u => u.Name.Contains(name));
21+
}
22+
23+
public void DeleteAll()
24+
{
25+
ColorConsole.WriteLineRepository($"Deleting all users");
26+
_users.Clear();
27+
}
28+
}
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net6.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
</PropertyGroup>
9+
10+
<ItemGroup>
11+
<PackageReference Include="MediatR" Version="10.0.1" />
12+
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="10.0.1" />
13+
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" />
14+
</ItemGroup>
15+
16+
</Project>

MediatorPattern/MediatorPattern.sln

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MediatorPattern", "MediatorPattern.csproj", "{A646458D-DD3E-49C4-91CB-6F9C1AC49B66}"
4+
EndProject
5+
Global
6+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
7+
Debug|Any CPU = Debug|Any CPU
8+
Release|Any CPU = Release|Any CPU
9+
EndGlobalSection
10+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
11+
{A646458D-DD3E-49C4-91CB-6F9C1AC49B66}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
12+
{A646458D-DD3E-49C4-91CB-6F9C1AC49B66}.Debug|Any CPU.Build.0 = Debug|Any CPU
13+
{A646458D-DD3E-49C4-91CB-6F9C1AC49B66}.Release|Any CPU.ActiveCfg = Release|Any CPU
14+
{A646458D-DD3E-49C4-91CB-6F9C1AC49B66}.Release|Any CPU.Build.0 = Release|Any CPU
15+
EndGlobalSection
16+
EndGlobal

MediatorPattern/Program.cs

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// See https://aka.ms/new-console-template for more information
2+
3+
using System.Drawing;
4+
using MediatorPattern;
5+
using MediatorPattern.Infrastructure;
6+
using MediatR;
7+
using Microsoft.Extensions.DependencyInjection;
8+
9+
Console.WriteLine("Legend:");
10+
11+
ColorConsole.WriteLineCommandHandler("Command - Handlers are blue");
12+
ColorConsole.WriteLineQueryHandler("Query - Handlers are yellow");
13+
ColorConsole.WriteLineProgram("Program code is green");
14+
ColorConsole.WriteLineRepository("Repository code is magenta");
15+
Console.WriteLine("------------------------");
16+
Console.WriteLine();
17+
18+
var serviceProvider = CreateServiceProvider();
19+
await serviceProvider.GetRequiredService<Execution>().RunAsync();
20+
21+
ServiceProvider CreateServiceProvider()
22+
{
23+
var collection = new ServiceCollection();
24+
collection.AddScoped<Execution>();
25+
collection.AddMediatR(typeof(Program).Assembly);
26+
collection.AddScoped<UserRepository>();
27+
return collection.BuildServiceProvider();
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
using MediatR;
2+
3+
namespace MediatorPattern.Query;
4+
5+
public class GetUserCountQuery : IRequest<int>
6+
{
7+
public string? NameFilter { get; set; }
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
using MediatorPattern.Infrastructure;
2+
using MediatR;
3+
4+
namespace MediatorPattern.Query;
5+
6+
public class GetUserCountQueryHandler : IRequestHandler<GetUserCountQuery, int>
7+
{
8+
private readonly UserRepository _userRepository;
9+
10+
public GetUserCountQueryHandler(UserRepository userRepository)
11+
{
12+
_userRepository = userRepository;
13+
}
14+
15+
public Task<int> Handle(GetUserCountQuery request, CancellationToken cancellationToken)
16+
{
17+
ColorConsole.WriteLineQueryHandler($"Getting count of users with name '{request.NameFilter}'");
18+
var count = _userRepository.GetUserCount(request.NameFilter);
19+
ColorConsole.WriteLineQueryHandler("Got count from repository and returning it back.");
20+
return Task.FromResult(count);
21+
}
22+
}

0 commit comments

Comments
 (0)