ASP.NET Core API using MediatR and FluentValidation to separate concerns with middleware for ValidationException error handling. Project contains template and sample ASP.NET Core application which is refactored classic ASP.NET Core API template (Weather Forecast App).
Important notes
Coresubfolder should be moved into separateCore.csprojclass libraryInfrastructuresubfolder should be moved intoInfrastructure.csprojMore info about Clean Architecture: https://jasontaylor.dev/clean-architecture-getting-started/
-
Add NuGet packages
dotnet add package MediatR dotnet add package MediatR.Extensions.Microsoft.DependencyInjection dotnet add package FluentValidation dotnet add package FluentValidation.DependencyInjectionExtensions -
Copy/Create unit:
ValidationErrorHandlingMiddleware.cs- link- Recommendations:
- extract ValidationPipelineBehavior class into the separate unit
- move it into Core/Behaviors directory
-
Update
Startup.cs:// Register method: services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationPipelineBehavior<,>)); var assembly = typeof(Startup).Assembly; services.AddMediatR(assembly); services.AddValidatorsFromAssembly(assembly); // Configure method: app.UseMiddleware<ValidationErrorHandlingMiddleware>();
-
Add Mediator Request and Handler (rename
Forecastto your domain subject)public class GetForecastQuery : IRequest<Forecast> { ... } public class GetForecastQueryHandler : IRequestHandler<GetForecastQuery, Forecast> { ... }
-
Add Fluent Validator
public class GetForecastQueryValidator : AbstractValidator<GetForecastQuery> { ... }