Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,377 changes: 1,377 additions & 0 deletions .editorconfig

Large diffs are not rendered by default.

21 changes: 21 additions & 0 deletions Directory.Build.props
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>
24 changes: 24 additions & 0 deletions Directory.Packages.props
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>
3 changes: 3 additions & 0 deletions VerticalSliceArchitectureTemplate.sln
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
global.json = global.json
LICENSE = LICENSE
README.md = README.md
Directory.Build.props = Directory.Build.props
Directory.Packages.props = Directory.Packages.props
.editorconfig = .editorconfig
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{92C5999C-A447-479E-8630-064E6FDC78DA}"
Expand Down
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;
}
}
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;
}
}
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;
}
}
}
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;
}
}
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);
}
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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@

public interface IFeature
{
public abstract static string FeatureName { get; }
static abstract void ConfigureServices(IServiceCollection services, IConfiguration config);
}
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);
}
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();
}
}
}
Loading