-
Notifications
You must be signed in to change notification settings - Fork 35
#101 ♻️ Replace Immediate.Handlers with MediatR #106
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
e1a8680
#101 Centrally managed packages
sam-s-maher 356d6f8
#101 Refactored Endpoints into MediatR pattern
sam-s-maher 083af61
#101 Added 'WithTags' and updated comments
sam-s-maher 51542cb
#101 Using OpenAPI & other updates as per discussions
sam-s-maher ca4e137
#101 Updated logging to avoid CA1848
sam-s-maher bd7dd56
#101 Added .editorconfig to allow for underscored test names
sam-s-maher 1c64b27
#101 Relocated global service configuration into AddApplication
sam-s-maher d1404a8
#101 Removed IEndpoints code
sam-s-maher 3955b3d
#101 Reverted StagedEvents refactor
sam-s-maher fb8e14e
#101 Small syntax change
sam-s-maher File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| <Project> | ||
| <PropertyGroup> | ||
| <TargetFramework>net8.0</TargetFramework> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <Nullable>enable</Nullable> | ||
| <TreatWarningsAsErrors Condition="'$(Configuration)' == 'Release'">true</TreatWarningsAsErrors> | ||
| <CodeAnalysisTreatWarningsAsErrors Condition="'$(Configuration)' == 'Release'">true</CodeAnalysisTreatWarningsAsErrors> | ||
|
|
||
| <AnalysisLevel>latest</AnalysisLevel> | ||
| <AnalysisMode>Recommended</AnalysisMode> | ||
|
|
||
| <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild> | ||
|
|
||
| <!-- Disable whitespace rule --> | ||
| <NoWarn>$(NoWarn);IDE0055</NoWarn> | ||
|
|
||
| <!-- Disable "must have curly braces for if/else" --> | ||
| <NoWarn>$(NoWarn);IDE0011</NoWarn> | ||
|
|
||
| </PropertyGroup> | ||
| </Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| <Project> | ||
| <PropertyGroup> | ||
| <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally> | ||
| </PropertyGroup> | ||
| <ItemGroup> | ||
| <PackageVersion Include="MediatR" Version="12.5.0" /> | ||
| <PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="8.0.4" /> | ||
| <PackageVersion Include="Microsoft.EntityFrameworkCore" Version="8.0.4" /> | ||
| <PackageVersion Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.4" /> | ||
| <PackageVersion Include="Swashbuckle.AspNetCore" Version="6.5.0" /> | ||
| <PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="11.11.0" /> | ||
| <PackageVersion Include="ErrorOr" Version="2.0.1" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup Condition="$(IsTestProject) == 'true'"> | ||
| <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.6.0" /> | ||
| <PackageVersion Include="xunit" Version="2.4.2" /> | ||
| <PackageVersion Include="xunit.runner.visualstudio" Version="2.4.5" /> | ||
| <PackageVersion Include="FluentAssertions" Version="6.12.0" /> | ||
| <PackageVersion Include="NSubstitute" Version="5.1.0" /> | ||
| <PackageVersion Include="NetArchTest.Rules" Version="1.3.2" /> | ||
| <PackageVersion Include="coverlet.collector" Version="6.0.0" /> | ||
| </ItemGroup> | ||
| </Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
31 changes: 31 additions & 0 deletions
31
src/VerticalSliceArchitectureTemplate/Common/Behaviours/LoggingBehaviour.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| using MediatR.Pipeline; | ||
| using VerticalSliceArchitectureTemplate.Common.Services; | ||
|
|
||
| namespace VerticalSliceArchitectureTemplate.Common.Behaviours; | ||
|
|
||
| public static class RequestInformationLogger | ||
| { | ||
| private static readonly Action<ILogger, string, object, object, Exception?> LogAction = | ||
| LoggerMessage.Define<string, object, object>( | ||
| LogLevel.Information, | ||
| new EventId(2, nameof(RequestInformationLogger)), | ||
| "CleanArchitecture Request: {Name} {@UserId} {@Request}"); | ||
|
|
||
| public static void Log(ILogger logger, string name, object userId, object request) => | ||
| LogAction(logger, name, userId, request, null); | ||
| } | ||
|
|
||
| public class LoggingBehaviour<TRequest>(ILogger<TRequest> logger, CurrentUserService currentUserService) | ||
| : IRequestPreProcessor<TRequest> | ||
| where TRequest : notnull | ||
| { | ||
| public Task Process(TRequest request, CancellationToken cancellationToken) | ||
| { | ||
| var requestName = typeof(TRequest).Name; | ||
| var userId = currentUserService.UserId ?? string.Empty; | ||
|
|
||
| RequestInformationLogger.Log(logger, requestName, userId, request); | ||
|
|
||
| return Task.CompletedTask; | ||
| } | ||
| } |
48 changes: 48 additions & 0 deletions
48
src/VerticalSliceArchitectureTemplate/Common/Behaviours/PerformanceBehaviour.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| using System.Diagnostics; | ||
| using MediatR; | ||
| using VerticalSliceArchitectureTemplate.Common.Services; | ||
|
|
||
| namespace VerticalSliceArchitectureTemplate.Common.Behaviours; | ||
|
|
||
| public static class LongRunningRequestLog | ||
| { | ||
| private static readonly Action<ILogger, string, long, string, object, Exception?> LogAction = | ||
| LoggerMessage.Define<string, long, string, object>( | ||
| LogLevel.Warning, | ||
| new EventId(3, nameof(LongRunningRequestLog)), | ||
| "VerticalSliceArchitecture Long Running Request: {Name} ({ElapsedMilliseconds} milliseconds) {@UserId} {@Request}"); | ||
|
|
||
| public static void Log(ILogger logger, string name, long elapsedMilliseconds, string userId, object request) => | ||
| LogAction(logger, name, elapsedMilliseconds, userId, request, null); | ||
| } | ||
|
|
||
| public class PerformanceBehaviour<TRequest, TResponse>( | ||
| ILogger<TRequest> logger, | ||
| CurrentUserService currentUserService) | ||
| : IPipelineBehavior<TRequest, TResponse> | ||
| where TRequest : notnull | ||
| { | ||
| private readonly Stopwatch _timer = new(); | ||
|
|
||
| public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| _timer.Start(); | ||
|
|
||
| var response = await next(cancellationToken); | ||
|
|
||
| _timer.Stop(); | ||
|
|
||
| var elapsedMilliseconds = _timer.ElapsedMilliseconds; | ||
|
|
||
| if (elapsedMilliseconds > 500) | ||
| { | ||
| var requestName = typeof(TRequest).Name; | ||
| var userId = currentUserService.UserId ?? string.Empty; | ||
|
|
||
| LongRunningRequestLog.Log(logger, requestName, elapsedMilliseconds, userId, request); | ||
| } | ||
|
|
||
| return response; | ||
| } | ||
| } |
37 changes: 37 additions & 0 deletions
37
src/VerticalSliceArchitectureTemplate/Common/Behaviours/UnhandledExceptionBehaviour.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| using MediatR; | ||
|
|
||
| namespace VerticalSliceArchitectureTemplate.Common.Behaviours; | ||
|
|
||
| public static class UnhandledExceptionBehaviourLogger | ||
| { | ||
| private static readonly Action<ILogger, string, object, Exception> LogAction = | ||
| LoggerMessage.Define<string, object>( | ||
| LogLevel.Error, | ||
| new EventId(1, nameof(UnhandledExceptionBehaviourLogger)), | ||
| "VerticalSliceArchitecture Request: Unhandled Exception for Request {Name} {@Request}"); | ||
|
|
||
| public static void Log(ILogger logger, string name, object request, Exception exception) => | ||
| LogAction(logger, name, request, exception); | ||
| } | ||
|
|
||
| public class UnhandledExceptionBehaviour<TRequest, TResponse>(ILogger<TRequest> logger) | ||
| : IPipelineBehavior<TRequest, TResponse> | ||
| where TRequest : notnull | ||
| { | ||
| public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| try | ||
| { | ||
| return await next(cancellationToken); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| var requestName = typeof(TRequest).Name; | ||
|
|
||
| UnhandledExceptionBehaviourLogger.Log(logger, requestName, request, ex); | ||
|
|
||
| throw; | ||
| } | ||
| } | ||
| } |
30 changes: 30 additions & 0 deletions
30
src/VerticalSliceArchitectureTemplate/Common/Behaviours/ValidationErrorOrResultBehaviour.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| using MediatR; | ||
|
|
||
| namespace VerticalSliceArchitectureTemplate.Common.Behaviours; | ||
|
|
||
| public class ValidationErrorOrResultBehavior<TRequest, TResponse>(IValidator<TRequest>? validator = null) | ||
| : IPipelineBehavior<TRequest, TResponse> | ||
| where TRequest : IRequest<TResponse> | ||
| where TResponse : IErrorOr | ||
| { | ||
| public async Task<TResponse> Handle( | ||
| TRequest request, | ||
| RequestHandlerDelegate<TResponse> next, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| if (validator is null) | ||
| return await next(cancellationToken); | ||
|
|
||
| var validationResult = await validator.ValidateAsync(request, cancellationToken); | ||
|
|
||
| if (validationResult.IsValid) | ||
| return await next(cancellationToken); | ||
|
|
||
| var errors = validationResult.Errors | ||
| .ConvertAll(error => Error.Validation( | ||
| code: error.PropertyName, | ||
| description: error.ErrorMessage)); | ||
|
|
||
| return (dynamic)errors; | ||
| } | ||
| } |
37 changes: 37 additions & 0 deletions
37
src/VerticalSliceArchitectureTemplate/Common/Extensions/EndpointRouteBuilderExt.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| namespace VerticalSliceArchitectureTemplate.Common.Extensions; | ||
|
|
||
| public static class EndpointRouteBuilderExt | ||
| { | ||
| /// <summary> | ||
| /// Used for GET endpoints that return one or more items. | ||
| /// </summary> | ||
| public static RouteHandlerBuilder ProducesGet<T>(this RouteHandlerBuilder builder) => builder | ||
| .Produces<T>(StatusCodes.Status200OK) | ||
| .Produces(StatusCodes.Status404NotFound) | ||
| .ProducesProblem(StatusCodes.Status500InternalServerError); | ||
|
|
||
| /// <summary> | ||
| /// Used for POST endpoints that creates a single item. | ||
| /// </summary> | ||
| public static RouteHandlerBuilder ProducesPost(this RouteHandlerBuilder builder) => builder | ||
| .Produces(StatusCodes.Status201Created) | ||
| .ProducesValidationProblem() | ||
| .ProducesProblem(StatusCodes.Status500InternalServerError); | ||
|
|
||
| /// <summary> | ||
| /// Used for PUT endpoints that updates a single item. | ||
| /// </summary> | ||
| public static RouteHandlerBuilder ProducesPut(this RouteHandlerBuilder builder) => builder | ||
| .Produces(StatusCodes.Status204NoContent) | ||
| .Produces(StatusCodes.Status404NotFound) | ||
| .ProducesValidationProblem() | ||
| .ProducesProblem(StatusCodes.Status500InternalServerError); | ||
|
|
||
| /// <summary> | ||
| /// Used for DELETE endpoints that deletes a single item. | ||
| /// </summary> | ||
| public static RouteHandlerBuilder ProducesDelete(this RouteHandlerBuilder builder) => builder | ||
| .Produces(StatusCodes.Status204NoContent) | ||
| .Produces(StatusCodes.Status404NotFound) | ||
| .ProducesProblem(StatusCodes.Status500InternalServerError); | ||
| } |
17 changes: 17 additions & 0 deletions
17
src/VerticalSliceArchitectureTemplate/Common/Extensions/WebApplicationExt.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| namespace VerticalSliceArchitectureTemplate.Common.Extensions; | ||
|
|
||
| public static class WebApplicationExt | ||
| { | ||
| /// <summary> | ||
| /// Adds an 'api' prefix to the route, and adds the group name as a tag and enables OpenAPI. | ||
| /// </summary> | ||
| public static RouteGroupBuilder MapApiGroup(this IEndpointRouteBuilder endpoints, string groupName) | ||
| { | ||
| var group = endpoints | ||
| .MapGroup($"api/{groupName.ToLowerInvariant()}") | ||
| .WithTags(groupName) | ||
| .WithOpenApi(); | ||
|
|
||
| return group; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
8 changes: 8 additions & 0 deletions
8
src/VerticalSliceArchitectureTemplate/Common/Services/CurrentUserService.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| using System.Security.Claims; | ||
|
|
||
| namespace VerticalSliceArchitectureTemplate.Common.Services; | ||
|
|
||
| public class CurrentUserService(IHttpContextAccessor httpContextAccessor) | ||
| { | ||
| public string? UserId => httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier); | ||
| } |
80 changes: 58 additions & 22 deletions
80
src/VerticalSliceArchitectureTemplate/Features/Todos/Commands/CompleteTodo.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,34 +1,70 @@ | ||
| using VerticalSliceArchitectureTemplate.Features.Todos.Domain; | ||
| using System.Text.Json.Serialization; | ||
| using MediatR; | ||
| using VerticalSliceArchitectureTemplate.Common.Extensions; | ||
| using VerticalSliceArchitectureTemplate.Features.Todos.Domain; | ||
|
|
||
| namespace VerticalSliceArchitectureTemplate.Features.Todos.Commands; | ||
|
|
||
|
|
||
| [Handler] | ||
| public sealed partial class CompleteTodo : IEndpoint | ||
| public static class CompleteTodo | ||
| { | ||
| public static void MapEndpoint(IEndpointRouteBuilder endpoints) | ||
| public record Request : IRequest<ErrorOr<Success>> | ||
| { | ||
| [JsonIgnore] | ||
| public Guid Id { get; set; } | ||
| } | ||
|
|
||
| public class Endpoint : IEndpoint | ||
| { | ||
| public static void MapEndpoint(IEndpointRouteBuilder endpoints) | ||
| { | ||
| endpoints | ||
| .MapApiGroup(TodoFeature.FeatureName) | ||
| .MapPut("/{id:guid}/complete", | ||
| async ( | ||
| Guid id, | ||
| ISender sender, | ||
| CancellationToken cancellationToken) => | ||
| { | ||
| var request = new Request { Id = id }; | ||
| await sender.Send(request, cancellationToken); | ||
| return Results.NoContent(); | ||
| }) | ||
| .WithName("CompleteTodo") | ||
| .ProducesPut(); | ||
| } | ||
| } | ||
|
|
||
| public class Validator : AbstractValidator<Request> | ||
| { | ||
| endpoints.MapPut("/todos/{id:guid}/complete", | ||
| async ([FromRoute] Guid id, Handler handler, CancellationToken cancellationToken) => | ||
| { | ||
| await handler.HandleAsync(new Command(id), cancellationToken); | ||
| return Results.NoContent(); | ||
| }) | ||
| .Produces(StatusCodes.Status204NoContent) | ||
| .Produces(StatusCodes.Status404NotFound) | ||
| .ProducesValidationProblem() | ||
| .ProducesProblem(StatusCodes.Status500InternalServerError) | ||
| .WithTags(nameof(Todo)); | ||
| public Validator() | ||
| { | ||
| RuleFor(r => r.Id) | ||
| .NotEmpty(); | ||
| } | ||
| } | ||
| public sealed record Command(Guid Id); | ||
| private static async ValueTask HandleAsync(Command request, AppDbContext dbContext, CancellationToken cancellationToken) | ||
|
|
||
| internal sealed class Handler : IRequestHandler<Request, ErrorOr<Success>> | ||
| { | ||
| var todo = await dbContext.Todos.FindAsync([request.Id], cancellationToken); | ||
| private readonly AppDbContext _dbContext; | ||
|
|
||
| public Handler(AppDbContext dbContext) | ||
| { | ||
| _dbContext = dbContext; | ||
| } | ||
|
|
||
| public async Task<ErrorOr<Success>> Handle( | ||
| Request request, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| var todo = await _dbContext.Todos.FindAsync([request.Id], cancellationToken); | ||
|
|
||
| if (todo == null) throw new NotFoundException(nameof(Todo), request.Id); | ||
|
|
||
| if (todo == null) throw new NotFoundException(nameof(Todo), request.Id); | ||
| todo.Complete(); | ||
|
|
||
| todo.Complete(); | ||
| await _dbContext.SaveChangesAsync(cancellationToken); | ||
|
|
||
| await dbContext.SaveChangesAsync(cancellationToken); | ||
| return new Success(); | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.