├── .gitignore ├── CQRS_Validation_FluentValidator ├── .dockerignore ├── Application │ ├── Abstractions │ │ └── Messaging │ │ │ ├── ICommand.cs │ │ │ ├── ICommandHandler.cs │ │ │ ├── IIdempotentCommand.cs │ │ │ ├── IQuery.cs │ │ │ └── IQueryHandler.cs │ ├── Application.csproj │ ├── AssemblyReference.cs │ ├── Behaviors │ │ └── ValidationBehavior.cs │ ├── Contracts │ │ └── Users │ │ │ └── UserResponse.cs │ ├── Exceptions │ │ └── ValidationException.cs │ └── Users │ │ ├── Commands │ │ ├── CreateUser │ │ │ ├── CreateUserCommand.cs │ │ │ ├── CreateUserCommandHandler.cs │ │ │ ├── CreateUserCommandValidator.cs │ │ │ └── CreateUserRequest.cs │ │ └── UpdateUser │ │ │ ├── UpdateUserCommand.cs │ │ │ ├── UpdateUserCommandHandler.cs │ │ │ ├── UpdateUserCommandValidator.cs │ │ │ └── UpdateUserRequest.cs │ │ └── Queries │ │ ├── GetUserById │ │ ├── GetUserByIdQuery.cs │ │ └── GetUserByIdQueryHandler.cs │ │ └── GetUsers │ │ ├── GetUsersQuery.cs │ │ └── GetUsersQueryHandler.cs ├── CQRS_Validation.sln ├── Domain │ ├── Domain.csproj │ ├── Entities │ │ └── User.cs │ ├── Exceptions │ │ ├── ApplicationException.cs │ │ ├── BadRequestException.cs │ │ ├── NotFoundException.cs │ │ └── UserNotFoundException.cs │ └── Repositories │ │ ├── IUnitOfWork.cs │ │ └── IUserRepository.cs ├── Persistence │ ├── ApplicationDbContext.cs │ ├── Configurations │ │ └── UserConfiguration.cs │ ├── Migrations │ │ ├── 20210809144538_InitialCreate.Designer.cs │ │ ├── 20210809144538_InitialCreate.cs │ │ └── ApplicationDbContextModelSnapshot.cs │ ├── Persistence.csproj │ └── Repositories │ │ ├── UnitOfWork.cs │ │ └── UserRepository.cs ├── Presentation │ ├── AssemblyReference.cs │ ├── Controllers │ │ └── UsersController.cs │ ├── Presentation.csproj │ └── Presentation.xml ├── Web │ ├── Dockerfile │ ├── Middleware │ │ └── ExceptionHandlingMiddleware.cs │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── Startup.cs │ ├── Web.csproj │ ├── appsettings.Development.json │ └── appsettings.json ├── docker-compose.dcproj ├── docker-compose.override.yml └── docker-compose.yml ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/.dockerignore: -------------------------------------------------------------------------------- 1 | **/.classpath 2 | **/.dockerignore 3 | **/.env 4 | **/.git 5 | **/.gitignore 6 | **/.project 7 | **/.settings 8 | **/.toolstarget 9 | **/.vs 10 | **/.vscode 11 | **/*.*proj.user 12 | **/*.dbmdl 13 | **/*.jfm 14 | **/azds.yaml 15 | **/bin 16 | **/charts 17 | **/docker-compose* 18 | **/Dockerfile* 19 | **/node_modules 20 | **/npm-debug.log 21 | **/obj 22 | **/secrets.dev.yaml 23 | **/values.dev.yaml 24 | LICENSE 25 | README.md -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Abstractions/Messaging/ICommand.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | 3 | namespace Application.Abstractions.Messaging 4 | { 5 | public interface ICommand : IRequest 6 | { 7 | } 8 | } -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Abstractions/Messaging/ICommandHandler.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | 3 | namespace Application.Abstractions.Messaging 4 | { 5 | public interface ICommandHandler : IRequestHandler 6 | where TCommand : ICommand 7 | { 8 | } 9 | } -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Abstractions/Messaging/IIdempotentCommand.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Application.Abstractions.Messaging 4 | { 5 | public interface IIdempotentCommand : ICommand 6 | { 7 | Guid RequestId { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Abstractions/Messaging/IQuery.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | 3 | namespace Application.Abstractions.Messaging 4 | { 5 | public interface IQuery : IRequest 6 | { 7 | } 8 | } -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Abstractions/Messaging/IQueryHandler.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | 3 | namespace Application.Abstractions.Messaging 4 | { 5 | public interface IQueryHandler : IRequestHandler 6 | where TQuery : IQuery 7 | { 8 | } 9 | } -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Application.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/AssemblyReference.cs: -------------------------------------------------------------------------------- 1 | namespace Application 2 | { 3 | public sealed record AssemblyReference; 4 | } 5 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Behaviors/ValidationBehavior.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using Application.Abstractions.Messaging; 6 | using FluentValidation; 7 | using MediatR; 8 | using ValidationException = Application.Exceptions.ValidationException; 9 | 10 | namespace Application.Behaviors 11 | { 12 | public sealed class ValidationBehavior : IPipelineBehavior 13 | where TRequest : class, ICommand 14 | { 15 | private readonly IEnumerable> _validators; 16 | 17 | public ValidationBehavior(IEnumerable> validators) => _validators = validators; 18 | 19 | public async Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next) 20 | { 21 | if (!_validators.Any()) 22 | { 23 | return await next(); 24 | } 25 | 26 | var context = new ValidationContext(request); 27 | 28 | var errorsDictionary = _validators 29 | .Select(x => x.Validate(context)) 30 | .SelectMany(x => x.Errors) 31 | .Where(x => x != null) 32 | .GroupBy( 33 | x => x.PropertyName, 34 | x => x.ErrorMessage, 35 | (propertyName, errorMessages) => new 36 | { 37 | Key = propertyName, 38 | Values = errorMessages.Distinct().ToArray() 39 | }) 40 | .ToDictionary(x => x.Key, x => x.Values); 41 | 42 | if (errorsDictionary.Any()) 43 | { 44 | throw new ValidationException(errorsDictionary); 45 | } 46 | 47 | return await next(); 48 | } 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Contracts/Users/UserResponse.cs: -------------------------------------------------------------------------------- 1 | namespace Application.Contracts.Users 2 | { 3 | public sealed record UserResponse(int Id, string FirstName, string LastName); 4 | } 5 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Exceptions/ValidationException.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using ApplicationException = Domain.Exceptions.ApplicationException; 3 | 4 | namespace Application.Exceptions 5 | { 6 | public sealed class ValidationException : ApplicationException 7 | { 8 | public ValidationException(IReadOnlyDictionary errorsDictionary) 9 | : base("Validation Failure", "One or more validation errors occurred") 10 | => ErrorsDictionary = errorsDictionary; 11 | 12 | public IReadOnlyDictionary ErrorsDictionary { get; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Users/Commands/CreateUser/CreateUserCommand.cs: -------------------------------------------------------------------------------- 1 | using Application.Abstractions.Messaging; 2 | using Application.Contracts.Users; 3 | 4 | namespace Application.Users.Commands.CreateUser 5 | { 6 | public sealed record CreateUserCommand(string FirstName, string LastName) : ICommand; 7 | } 8 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Users/Commands/CreateUser/CreateUserCommandHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | using System.Threading.Tasks; 3 | using Application.Abstractions.Messaging; 4 | using Application.Contracts.Users; 5 | using Domain.Entities; 6 | using Domain.Repositories; 7 | using Mapster; 8 | 9 | namespace Application.Users.Commands.CreateUser 10 | { 11 | internal sealed class CreateUserCommandHandler : ICommandHandler 12 | { 13 | private readonly IUserRepository _userRepository; 14 | private readonly IUnitOfWork _unitOfWork; 15 | 16 | public CreateUserCommandHandler(IUserRepository userRepository, IUnitOfWork unitOfWork) 17 | { 18 | _userRepository = userRepository; 19 | _unitOfWork = unitOfWork; 20 | } 21 | 22 | public async Task Handle(CreateUserCommand request, CancellationToken cancellationToken) 23 | { 24 | var user = new User(request.FirstName, request.LastName); 25 | 26 | _userRepository.Insert(user); 27 | 28 | await _unitOfWork.SaveChangesAsync(cancellationToken); 29 | 30 | return user.Adapt(); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Users/Commands/CreateUser/CreateUserCommandValidator.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | 3 | namespace Application.Users.Commands.CreateUser 4 | { 5 | public sealed class CreateUserCommandValidator : AbstractValidator 6 | { 7 | public CreateUserCommandValidator() 8 | { 9 | RuleFor(x => x.FirstName).NotEmpty().MaximumLength(100); 10 | 11 | RuleFor(x => x.LastName).NotEmpty().MaximumLength(100); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Users/Commands/CreateUser/CreateUserRequest.cs: -------------------------------------------------------------------------------- 1 | namespace Application.Users.Commands.CreateUser 2 | { 3 | public sealed record CreateUserRequest(string FirstName, string LastName); 4 | } 5 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Users/Commands/UpdateUser/UpdateUserCommand.cs: -------------------------------------------------------------------------------- 1 | using Application.Abstractions.Messaging; 2 | using MediatR; 3 | 4 | namespace Application.Users.Commands.UpdateUser 5 | { 6 | public sealed record UpdateUserCommand(int UserId, string FirstName, string LastName) : ICommand; 7 | } 8 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Users/Commands/UpdateUser/UpdateUserCommandHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | using System.Threading.Tasks; 3 | using Application.Abstractions.Messaging; 4 | using Domain.Exceptions; 5 | using Domain.Repositories; 6 | using MediatR; 7 | 8 | namespace Application.Users.Commands.UpdateUser 9 | { 10 | internal sealed class UpdateUserCommandHandler : ICommandHandler 11 | { 12 | private readonly IUserRepository _userRepository; 13 | private readonly IUnitOfWork _unitOfWork; 14 | 15 | public UpdateUserCommandHandler(IUserRepository userRepository, IUnitOfWork unitOfWork) 16 | { 17 | _userRepository = userRepository; 18 | _unitOfWork = unitOfWork; 19 | } 20 | 21 | public async Task Handle(UpdateUserCommand request, CancellationToken cancellationToken) 22 | { 23 | var user = await _userRepository.GetByIdAsync(request.UserId, cancellationToken); 24 | 25 | if (user is null) 26 | { 27 | throw new UserNotFoundException(request.UserId); 28 | } 29 | 30 | user.Update(request.FirstName, request.LastName); 31 | 32 | await _unitOfWork.SaveChangesAsync(cancellationToken); 33 | 34 | return Unit.Value; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Users/Commands/UpdateUser/UpdateUserCommandValidator.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | 3 | namespace Application.Users.Commands.UpdateUser 4 | { 5 | public sealed class UpdateUserCommandValidator : AbstractValidator 6 | { 7 | public UpdateUserCommandValidator() 8 | { 9 | RuleFor(x => x.UserId).NotEmpty(); 10 | 11 | RuleFor(x => x.FirstName).NotEmpty().MaximumLength(100); 12 | 13 | RuleFor(x => x.LastName).NotEmpty().MaximumLength(100); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Users/Commands/UpdateUser/UpdateUserRequest.cs: -------------------------------------------------------------------------------- 1 | namespace Application.Users.Commands.UpdateUser 2 | { 3 | public sealed record UpdateUserRequest(string FirstName, string LastName); 4 | } 5 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Users/Queries/GetUserById/GetUserByIdQuery.cs: -------------------------------------------------------------------------------- 1 | using Application.Abstractions.Messaging; 2 | using Application.Contracts.Users; 3 | 4 | namespace Application.Users.Queries.GetUserById 5 | { 6 | public sealed record GetUserByIdQuery(int UserId) : IQuery; 7 | } 8 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Users/Queries/GetUserById/GetUserByIdQueryHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | using System.Threading.Tasks; 3 | using Application.Abstractions.Messaging; 4 | using Application.Contracts.Users; 5 | using Domain.Exceptions; 6 | using Domain.Repositories; 7 | using Mapster; 8 | 9 | namespace Application.Users.Queries.GetUserById 10 | { 11 | internal sealed class GetUserByIdQueryHandler : IQueryHandler 12 | { 13 | private readonly IUserRepository _userRepository; 14 | 15 | public GetUserByIdQueryHandler(IUserRepository userRepository) => _userRepository = userRepository; 16 | 17 | public async Task Handle(GetUserByIdQuery request, CancellationToken cancellationToken) 18 | { 19 | var user = await _userRepository.GetByIdAsync(request.UserId, cancellationToken); 20 | 21 | if (user is null) 22 | { 23 | throw new UserNotFoundException(request.UserId); 24 | } 25 | 26 | return user.Adapt(); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Users/Queries/GetUsers/GetUsersQuery.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Application.Abstractions.Messaging; 3 | using Application.Contracts.Users; 4 | 5 | namespace Application.Users.Queries.GetUsers 6 | { 7 | public sealed record GetUsersQuery() : IQuery>; 8 | } 9 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Application/Users/Queries/GetUsers/GetUsersQueryHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using Application.Abstractions.Messaging; 5 | using Application.Contracts.Users; 6 | using Domain.Repositories; 7 | using Mapster; 8 | 9 | namespace Application.Users.Queries.GetUsers 10 | { 11 | internal sealed class GetUsersQueryHandler : IQueryHandler> 12 | { 13 | private readonly IUserRepository _userRepository; 14 | 15 | public GetUsersQueryHandler(IUserRepository userRepository) => _userRepository = userRepository; 16 | 17 | public async Task> Handle(GetUsersQuery request, CancellationToken cancellationToken) 18 | { 19 | var users = await _userRepository.GetAsync(cancellationToken); 20 | 21 | return users.Adapt>(); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/CQRS_Validation.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31424.327 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{E53339B2-1760-4266-BCC7-CA923CBCF16C}") = "docker-compose", "docker-compose.dcproj", "{EFDB57CC-0524-473D-B399-A0E6FDCC54B8}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Web", "Web\Web.csproj", "{A2E4667B-4385-4779-84D1-08A26B4C6164}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Presentation", "Presentation\Presentation.csproj", "{69E4E0BC-E51C-4CF7-817B-7051A2AFFDA0}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Domain", "Domain\Domain.csproj", "{694B3EDD-23A6-4BD3-B9AD-B44E99D4D347}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Persistence", "Persistence\Persistence.csproj", "{1A64D166-C256-4B85-96F8-1B20A99D7617}" 15 | EndProject 16 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Infrastructure", "Infrastructure", "{7026382D-0881-411D-9C76-2F4FD10B3B2B}" 17 | EndProject 18 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{34A9601A-F4A1-49DB-8C59-201E85C7F350}" 19 | EndProject 20 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Application", "Application\Application.csproj", "{06AA82D2-38AE-4E1A-ADF4-1B2F6130AEE7}" 21 | EndProject 22 | Global 23 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 24 | Debug|Any CPU = Debug|Any CPU 25 | Release|Any CPU = Release|Any CPU 26 | EndGlobalSection 27 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 28 | {EFDB57CC-0524-473D-B399-A0E6FDCC54B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {EFDB57CC-0524-473D-B399-A0E6FDCC54B8}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {EFDB57CC-0524-473D-B399-A0E6FDCC54B8}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {EFDB57CC-0524-473D-B399-A0E6FDCC54B8}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {A2E4667B-4385-4779-84D1-08A26B4C6164}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {A2E4667B-4385-4779-84D1-08A26B4C6164}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {A2E4667B-4385-4779-84D1-08A26B4C6164}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {A2E4667B-4385-4779-84D1-08A26B4C6164}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {69E4E0BC-E51C-4CF7-817B-7051A2AFFDA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {69E4E0BC-E51C-4CF7-817B-7051A2AFFDA0}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {69E4E0BC-E51C-4CF7-817B-7051A2AFFDA0}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {69E4E0BC-E51C-4CF7-817B-7051A2AFFDA0}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {694B3EDD-23A6-4BD3-B9AD-B44E99D4D347}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {694B3EDD-23A6-4BD3-B9AD-B44E99D4D347}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {694B3EDD-23A6-4BD3-B9AD-B44E99D4D347}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {694B3EDD-23A6-4BD3-B9AD-B44E99D4D347}.Release|Any CPU.Build.0 = Release|Any CPU 44 | {1A64D166-C256-4B85-96F8-1B20A99D7617}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 45 | {1A64D166-C256-4B85-96F8-1B20A99D7617}.Debug|Any CPU.Build.0 = Debug|Any CPU 46 | {1A64D166-C256-4B85-96F8-1B20A99D7617}.Release|Any CPU.ActiveCfg = Release|Any CPU 47 | {1A64D166-C256-4B85-96F8-1B20A99D7617}.Release|Any CPU.Build.0 = Release|Any CPU 48 | {06AA82D2-38AE-4E1A-ADF4-1B2F6130AEE7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 49 | {06AA82D2-38AE-4E1A-ADF4-1B2F6130AEE7}.Debug|Any CPU.Build.0 = Debug|Any CPU 50 | {06AA82D2-38AE-4E1A-ADF4-1B2F6130AEE7}.Release|Any CPU.ActiveCfg = Release|Any CPU 51 | {06AA82D2-38AE-4E1A-ADF4-1B2F6130AEE7}.Release|Any CPU.Build.0 = Release|Any CPU 52 | EndGlobalSection 53 | GlobalSection(SolutionProperties) = preSolution 54 | HideSolutionNode = FALSE 55 | EndGlobalSection 56 | GlobalSection(NestedProjects) = preSolution 57 | {69E4E0BC-E51C-4CF7-817B-7051A2AFFDA0} = {7026382D-0881-411D-9C76-2F4FD10B3B2B} 58 | {694B3EDD-23A6-4BD3-B9AD-B44E99D4D347} = {34A9601A-F4A1-49DB-8C59-201E85C7F350} 59 | {1A64D166-C256-4B85-96F8-1B20A99D7617} = {7026382D-0881-411D-9C76-2F4FD10B3B2B} 60 | {06AA82D2-38AE-4E1A-ADF4-1B2F6130AEE7} = {34A9601A-F4A1-49DB-8C59-201E85C7F350} 61 | EndGlobalSection 62 | GlobalSection(ExtensibilityGlobals) = postSolution 63 | SolutionGuid = {F7088B24-0DBE-4149-83C5-9BBE47BA04C1} 64 | EndGlobalSection 65 | EndGlobal 66 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Domain/Domain.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Domain/Entities/User.cs: -------------------------------------------------------------------------------- 1 | namespace Domain.Entities 2 | { 3 | public sealed class User 4 | { 5 | public User(string firstName, string lastName) 6 | : this() 7 | { 8 | FirstName = firstName; 9 | LastName = lastName; 10 | } 11 | 12 | private User() 13 | { 14 | } 15 | 16 | public int Id { get; private set; } 17 | 18 | public string FirstName { get; private set; } 19 | 20 | public string LastName { get; private set; } 21 | 22 | public void Update(string firstName, string lastName) => (FirstName, LastName) = (firstName, lastName); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Domain/Exceptions/ApplicationException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Domain.Exceptions 4 | { 5 | public abstract class ApplicationException : Exception 6 | { 7 | protected ApplicationException(string title, string message) 8 | : base(message) => 9 | Title = title; 10 | 11 | public string Title { get; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Domain/Exceptions/BadRequestException.cs: -------------------------------------------------------------------------------- 1 | namespace Domain.Exceptions 2 | { 3 | public abstract class BadRequestException : ApplicationException 4 | { 5 | protected BadRequestException(string message) 6 | : base("Bad Request", message) 7 | { 8 | } 9 | } 10 | } -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Domain/Exceptions/NotFoundException.cs: -------------------------------------------------------------------------------- 1 | namespace Domain.Exceptions 2 | { 3 | public abstract class NotFoundException : ApplicationException 4 | { 5 | protected NotFoundException(string message) 6 | : base("Not Found", message) 7 | { 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Domain/Exceptions/UserNotFoundException.cs: -------------------------------------------------------------------------------- 1 | namespace Domain.Exceptions 2 | { 3 | public sealed class UserNotFoundException : NotFoundException 4 | { 5 | public UserNotFoundException(int userId) 6 | : base($"The user with the identifier {userId} was not found.") 7 | { 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Domain/Repositories/IUnitOfWork.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | using System.Threading.Tasks; 3 | 4 | namespace Domain.Repositories 5 | { 6 | public interface IUnitOfWork 7 | { 8 | Task SaveChangesAsync(CancellationToken cancellationToken = default); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Domain/Repositories/IUserRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using Domain.Entities; 5 | 6 | namespace Domain.Repositories 7 | { 8 | public interface IUserRepository 9 | { 10 | Task> GetAsync(CancellationToken cancellationToken = default); 11 | 12 | Task GetByIdAsync(int userId, CancellationToken cancellationToken = default); 13 | 14 | void Insert(User user); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Persistence/ApplicationDbContext.cs: -------------------------------------------------------------------------------- 1 | using Domain.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | 4 | namespace Persistence 5 | { 6 | public sealed class ApplicationDbContext : DbContext 7 | { 8 | public ApplicationDbContext(DbContextOptions options) 9 | : base(options) 10 | { 11 | } 12 | 13 | public DbSet Users { get; set; } 14 | 15 | protected override void OnModelCreating(ModelBuilder modelBuilder) => 16 | modelBuilder.ApplyConfigurationsFromAssembly(typeof(ApplicationDbContext).Assembly); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Persistence/Configurations/UserConfiguration.cs: -------------------------------------------------------------------------------- 1 | using Domain.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 4 | 5 | namespace Persistence.Configurations 6 | { 7 | internal sealed class UserConfiguration : IEntityTypeConfiguration 8 | { 9 | public void Configure(EntityTypeBuilder builder) 10 | { 11 | builder.ToTable(nameof(User)); 12 | 13 | builder.HasKey(user => user.Id); 14 | 15 | builder.Property(user => user.Id).ValueGeneratedOnAdd(); 16 | 17 | builder.Property(user => user.FirstName).IsRequired().HasMaxLength(100); 18 | 19 | builder.Property(user => user.LastName).IsRequired().HasMaxLength(100); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Persistence/Migrations/20210809144538_InitialCreate.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Migrations; 5 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 6 | using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; 7 | using Persistence; 8 | 9 | namespace Persistence.Migrations 10 | { 11 | [DbContext(typeof(ApplicationDbContext))] 12 | [Migration("20210809144538_InitialCreate")] 13 | partial class InitialCreate 14 | { 15 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 16 | { 17 | #pragma warning disable 612, 618 18 | modelBuilder 19 | .HasAnnotation("Relational:MaxIdentifierLength", 63) 20 | .HasAnnotation("ProductVersion", "5.0.7") 21 | .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); 22 | 23 | modelBuilder.Entity("Domain.Entities.User", b => 24 | { 25 | b.Property("Id") 26 | .ValueGeneratedOnAdd() 27 | .HasColumnType("integer") 28 | .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); 29 | 30 | b.Property("FirstName") 31 | .IsRequired() 32 | .HasMaxLength(100) 33 | .HasColumnType("character varying(100)"); 34 | 35 | b.Property("LastName") 36 | .IsRequired() 37 | .HasMaxLength(100) 38 | .HasColumnType("character varying(100)"); 39 | 40 | b.HasKey("Id"); 41 | 42 | b.ToTable("User"); 43 | }); 44 | #pragma warning restore 612, 618 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Persistence/Migrations/20210809144538_InitialCreate.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; 4 | 5 | namespace Persistence.Migrations 6 | { 7 | public partial class InitialCreate : Migration 8 | { 9 | protected override void Up(MigrationBuilder migrationBuilder) 10 | { 11 | migrationBuilder.CreateTable( 12 | name: "User", 13 | columns: table => new 14 | { 15 | Id = table.Column(type: "integer", nullable: false) 16 | .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), 17 | FirstName = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), 18 | LastName = table.Column(type: "character varying(100)", maxLength: 100, nullable: false) 19 | }, 20 | constraints: table => 21 | { 22 | table.PrimaryKey("PK_User", x => x.Id); 23 | }); 24 | } 25 | 26 | protected override void Down(MigrationBuilder migrationBuilder) 27 | { 28 | migrationBuilder.DropTable( 29 | name: "User"); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Persistence/Migrations/ApplicationDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 5 | using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; 6 | using Persistence; 7 | 8 | namespace Persistence.Migrations 9 | { 10 | [DbContext(typeof(ApplicationDbContext))] 11 | partial class ApplicationDbContextModelSnapshot : ModelSnapshot 12 | { 13 | protected override void BuildModel(ModelBuilder modelBuilder) 14 | { 15 | #pragma warning disable 612, 618 16 | modelBuilder 17 | .HasAnnotation("Relational:MaxIdentifierLength", 63) 18 | .HasAnnotation("ProductVersion", "5.0.7") 19 | .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); 20 | 21 | modelBuilder.Entity("Domain.Entities.User", b => 22 | { 23 | b.Property("Id") 24 | .ValueGeneratedOnAdd() 25 | .HasColumnType("integer") 26 | .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); 27 | 28 | b.Property("FirstName") 29 | .IsRequired() 30 | .HasMaxLength(100) 31 | .HasColumnType("character varying(100)"); 32 | 33 | b.Property("LastName") 34 | .IsRequired() 35 | .HasMaxLength(100) 36 | .HasColumnType("character varying(100)"); 37 | 38 | b.HasKey("Id"); 39 | 40 | b.ToTable("User"); 41 | }); 42 | #pragma warning restore 612, 618 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Persistence/Persistence.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Persistence/Repositories/UnitOfWork.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | using System.Threading.Tasks; 3 | using Domain.Repositories; 4 | 5 | namespace Persistence.Repositories 6 | { 7 | public sealed class UnitOfWork : IUnitOfWork 8 | { 9 | private readonly ApplicationDbContext _dbContext; 10 | 11 | public UnitOfWork(ApplicationDbContext dbContext) => _dbContext = dbContext; 12 | 13 | public Task SaveChangesAsync(CancellationToken cancellationToken = default) => 14 | _dbContext.SaveChangesAsync(cancellationToken); 15 | } 16 | } -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Persistence/Repositories/UserRepository.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using Domain.Entities; 6 | using Domain.Repositories; 7 | using Microsoft.EntityFrameworkCore; 8 | 9 | namespace Persistence.Repositories 10 | { 11 | public sealed class UserRepository : IUserRepository 12 | { 13 | private readonly ApplicationDbContext _dbContext; 14 | 15 | public UserRepository(ApplicationDbContext dbContext) => _dbContext = dbContext; 16 | 17 | public Task> GetAsync(CancellationToken cancellationToken = default) => 18 | _dbContext.Users.ToListAsync(cancellationToken); 19 | 20 | public Task GetByIdAsync(int userId, CancellationToken cancellationToken = default) => 21 | _dbContext.Users.FirstOrDefaultAsync(user => user.Id == userId, cancellationToken); 22 | 23 | public void Insert(User user) => _dbContext.Users.Add(user); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Presentation/AssemblyReference.cs: -------------------------------------------------------------------------------- 1 | namespace Presentation 2 | { 3 | public static class AssemblyReference 4 | { 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Presentation/Controllers/UsersController.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using Application.Contracts.Users; 5 | using Application.Users.Commands.CreateUser; 6 | using Application.Users.Commands.UpdateUser; 7 | using Application.Users.Queries.GetUserById; 8 | using Application.Users.Queries.GetUsers; 9 | using Mapster; 10 | using MediatR; 11 | using Microsoft.AspNetCore.Http; 12 | using Microsoft.AspNetCore.Mvc; 13 | 14 | namespace Presentation.Controllers 15 | { 16 | /// 17 | /// The users controller. 18 | /// 19 | [ApiController] 20 | [Route("api/[controller]")] 21 | public sealed class UsersController : ControllerBase 22 | { 23 | private readonly ISender _sender; 24 | 25 | /// 26 | /// Initializes a new instance of the class. 27 | /// 28 | /// 29 | public UsersController(ISender sender) => _sender = sender; 30 | 31 | /// 32 | /// Gets all of the users. 33 | /// 34 | /// The cancellation token. 35 | /// The collection of users. 36 | [HttpGet] 37 | [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] 38 | public async Task GetUsers(CancellationToken cancellationToken) 39 | { 40 | var query = new GetUsersQuery(); 41 | 42 | var users = await _sender.Send(query, cancellationToken); 43 | 44 | return Ok(users); 45 | } 46 | 47 | /// 48 | /// Gets the user with the specified identifier, if it exists. 49 | /// 50 | /// The user identifier. 51 | /// The cancellation token. 52 | /// The user with the specified identifier, if it exists. 53 | [HttpGet("{userId:int}")] 54 | [ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)] 55 | [ProducesResponseType(StatusCodes.Status404NotFound)] 56 | public async Task GetUserById(int userId, CancellationToken cancellationToken) 57 | { 58 | var query = new GetUserByIdQuery(userId); 59 | 60 | var user = await _sender.Send(query, cancellationToken); 61 | 62 | return Ok(user); 63 | } 64 | 65 | /// 66 | /// Creates a new user based on the specified request. 67 | /// 68 | /// The create user request. 69 | /// The cancellation token. 70 | /// The newly created user. 71 | [HttpPost] 72 | [ProducesResponseType(typeof(UserResponse), StatusCodes.Status201Created)] 73 | public async Task CreateUser([FromBody] CreateUserRequest request, CancellationToken cancellationToken) 74 | { 75 | var command = request.Adapt(); 76 | 77 | var user = await _sender.Send(command, cancellationToken); 78 | 79 | return CreatedAtAction(nameof(GetUserById), new { userId = user.Id }, user); 80 | } 81 | 82 | /// 83 | /// Updates the user with the specified identifier based on the specified request, if it exists. 84 | /// 85 | /// The user identifier. 86 | /// The update user request. 87 | /// The cancellation token. 88 | /// No content. 89 | [HttpPut("{userId:int}")] 90 | [ProducesResponseType(StatusCodes.Status204NoContent)] 91 | [ProducesResponseType(StatusCodes.Status404NotFound)] 92 | public async Task UpdateUser(int userId, [FromBody] UpdateUserRequest request, CancellationToken cancellationToken) 93 | { 94 | var command = request.Adapt() with 95 | { 96 | UserId = userId 97 | }; 98 | 99 | await _sender.Send(command, cancellationToken); 100 | 101 | return NoContent(); 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Presentation/Presentation.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | Presentation.xml 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Presentation/Presentation.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Presentation 5 | 6 | 7 | 8 | 9 | The users controller. 10 | 11 | 12 | 13 | 14 | Initializes a new instance of the class. 15 | 16 | 17 | 18 | 19 | 20 | Gets all of the users. 21 | 22 | The cancellation token. 23 | The collection of users. 24 | 25 | 26 | 27 | Gets the user with the specified identifier, if it exists. 28 | 29 | The user identifier. 30 | The cancellation token. 31 | The user with the specified identifier, if it exists. 32 | 33 | 34 | 35 | Creates a new user based on the specified request. 36 | 37 | The create user request. 38 | The cancellation token. 39 | The newly created user. 40 | 41 | 42 | 43 | Updates the user with the specified identifier based on the specified request, if it exists. 44 | 45 | The user identifier. 46 | The update user request. 47 | The cancellation token. 48 | No content. 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Web/Dockerfile: -------------------------------------------------------------------------------- 1 | #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. 2 | 3 | FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base 4 | WORKDIR /app 5 | EXPOSE 80 6 | EXPOSE 443 7 | 8 | FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build 9 | WORKDIR /src 10 | COPY ["Web/Web.csproj", "Web/"] 11 | RUN dotnet restore "Web/Web.csproj" 12 | COPY . . 13 | WORKDIR "/src/Web" 14 | RUN dotnet build "Web.csproj" -c Release -o /app/build 15 | 16 | FROM build AS publish 17 | RUN dotnet publish "Web.csproj" -c Release -o /app/publish 18 | 19 | FROM base AS final 20 | WORKDIR /app 21 | COPY --from=publish /app/publish . 22 | ENTRYPOINT ["dotnet", "Web.dll"] -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Web/Middleware/ExceptionHandlingMiddleware.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text.Json; 4 | using System.Threading.Tasks; 5 | using Application.Exceptions; 6 | using Domain.Exceptions; 7 | using Microsoft.AspNetCore.Http; 8 | using Microsoft.Extensions.Logging; 9 | using ApplicationException = Domain.Exceptions.ApplicationException; 10 | 11 | namespace Web.Middleware 12 | { 13 | internal sealed class ExceptionHandlingMiddleware : IMiddleware 14 | { 15 | private readonly ILogger _logger; 16 | 17 | public ExceptionHandlingMiddleware(ILogger logger) => _logger = logger; 18 | 19 | public async Task InvokeAsync(HttpContext context, RequestDelegate next) 20 | { 21 | try 22 | { 23 | await next(context); 24 | } 25 | catch (Exception e) 26 | { 27 | _logger.LogError(e, e.Message); 28 | 29 | await HandleExceptionAsync(context, e); 30 | } 31 | } 32 | 33 | private static async Task HandleExceptionAsync(HttpContext httpContext, Exception exception) 34 | { 35 | var statusCode = GetStatusCode(exception); 36 | 37 | var response = new 38 | { 39 | title = GetTitle(exception), 40 | status = statusCode, 41 | detail = exception.Message, 42 | errors = GetErrors(exception) 43 | }; 44 | 45 | httpContext.Response.ContentType = "application/json"; 46 | 47 | httpContext.Response.StatusCode = statusCode; 48 | 49 | await httpContext.Response.WriteAsync(JsonSerializer.Serialize(response)); 50 | } 51 | 52 | private static int GetStatusCode(Exception exception) => 53 | exception switch 54 | { 55 | BadRequestException => StatusCodes.Status400BadRequest, 56 | NotFoundException => StatusCodes.Status404NotFound, 57 | ValidationException => StatusCodes.Status422UnprocessableEntity, 58 | _ => StatusCodes.Status500InternalServerError 59 | }; 60 | 61 | private static string GetTitle(Exception exception) => 62 | exception switch 63 | { 64 | ApplicationException applicationException => applicationException.Title, 65 | _ => "Server Error" 66 | }; 67 | 68 | private static IReadOnlyDictionary GetErrors(Exception exception) 69 | { 70 | IReadOnlyDictionary errors = null; 71 | 72 | if (exception is ValidationException validationException) 73 | { 74 | errors = validationException.ErrorsDictionary; 75 | } 76 | 77 | return errors; 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Web/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using Microsoft.AspNetCore.Hosting; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Hosting; 7 | using Persistence; 8 | 9 | namespace Web 10 | { 11 | public class Program 12 | { 13 | public static async Task Main(string[] args) 14 | { 15 | var webHost = CreateHostBuilder(args).Build(); 16 | 17 | await ApplyMigrations(webHost.Services); 18 | 19 | await webHost.RunAsync(); 20 | } 21 | 22 | private static async Task ApplyMigrations(IServiceProvider serviceProvider) 23 | { 24 | using var scope = serviceProvider.CreateScope(); 25 | 26 | await using ApplicationDbContext dbContext = scope.ServiceProvider.GetRequiredService(); 27 | 28 | await dbContext.Database.MigrateAsync(); 29 | } 30 | 31 | public static IHostBuilder CreateHostBuilder(string[] args) => 32 | Host.CreateDefaultBuilder(args) 33 | .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup()); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Web/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:13749", 7 | "sslPort": 44319 8 | } 9 | }, 10 | "$schema": "http://json.schemastore.org/launchsettings.json", 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "swagger", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "OnionArchitecutre.Web": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "swagger", 24 | "environmentVariables": { 25 | "ASPNETCORE_ENVIRONMENT": "Development" 26 | }, 27 | "dotnetRunMessages": "true", 28 | "applicationUrl": "https://localhost:5001;http://localhost:5000" 29 | }, 30 | "Docker": { 31 | "commandName": "Docker", 32 | "launchBrowser": true, 33 | "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger", 34 | "publishAllPorts": true, 35 | "useSSL": true 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Web/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using Application.Behaviors; 4 | using Domain.Repositories; 5 | using FluentValidation; 6 | using MediatR; 7 | using Microsoft.AspNetCore.Builder; 8 | using Microsoft.AspNetCore.Hosting; 9 | using Microsoft.EntityFrameworkCore; 10 | using Microsoft.Extensions.Configuration; 11 | using Microsoft.Extensions.DependencyInjection; 12 | using Microsoft.Extensions.Hosting; 13 | using Microsoft.OpenApi.Models; 14 | using Persistence; 15 | using Persistence.Repositories; 16 | using Web.Middleware; 17 | 18 | namespace Web 19 | { 20 | public class Startup 21 | { 22 | public Startup(IConfiguration configuration) => Configuration = configuration; 23 | 24 | public IConfiguration Configuration { get; } 25 | 26 | public void ConfigureServices(IServiceCollection services) 27 | { 28 | var presentationAssembly = typeof(Presentation.AssemblyReference).Assembly; 29 | 30 | services.AddControllers() 31 | .AddApplicationPart(presentationAssembly); 32 | 33 | services.AddSwaggerGen(c => 34 | { 35 | string presentationDocumentationFile = $"{presentationAssembly.GetName().Name}.xml"; 36 | 37 | string presentationDocumentationFilePath = Path.Combine(AppContext.BaseDirectory, presentationDocumentationFile); 38 | 39 | c.IncludeXmlComments(presentationDocumentationFilePath); 40 | 41 | c.SwaggerDoc("v1", new OpenApiInfo {Title = "Web", Version = "v1"}); 42 | }); 43 | 44 | services.AddDbContextPool(builder => 45 | { 46 | var connectionString = Configuration.GetConnectionString("Database"); 47 | 48 | builder.UseNpgsql(connectionString); 49 | }); 50 | 51 | services.AddScoped(); 52 | 53 | services.AddScoped(); 54 | 55 | services.AddTransient(); 56 | 57 | var applicationAssembly = typeof(Application.AssemblyReference).Assembly; 58 | 59 | services.AddMediatR(applicationAssembly); 60 | 61 | services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>)); 62 | 63 | services.AddValidatorsFromAssembly(applicationAssembly); 64 | } 65 | 66 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 67 | { 68 | if (env.IsDevelopment()) 69 | { 70 | app.UseDeveloperExceptionPage(); 71 | 72 | app.UseSwagger(); 73 | 74 | app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Web v1")); 75 | } 76 | 77 | app.UseMiddleware(); 78 | 79 | app.UseHttpsRedirection(); 80 | 81 | app.UseRouting(); 82 | 83 | app.UseAuthorization(); 84 | 85 | app.UseEndpoints(endpoints => endpoints.MapControllers()); 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Web/Web.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 540db5be-b2a8-4c4d-ace3-5761b60b3c97 6 | Linux 7 | ..\docker-compose.dcproj 8 | 9 | 10 | 11 | 12 | 13 | 14 | all 15 | runtime; build; native; contentfiles; analyzers; buildtransitive 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Web/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Information", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "ConnectionStrings": { 10 | "Database": "Host=codemaze.db;Port=5432;Database=users;User Id=postgres;Password=postgres;" 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/Web/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*" 10 | } 11 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/docker-compose.dcproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 2.1 5 | Linux 6 | efdb57cc-0524-473d-b399-a0e6fdcc54b8 7 | LaunchBrowser 8 | {Scheme}://localhost:{ServicePort}/swagger 9 | CQRS.Validation 10 | 11 | 12 | 13 | docker-compose.yml 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/docker-compose.override.yml: -------------------------------------------------------------------------------- 1 | version: '3.4' 2 | 3 | services: 4 | codemaze.web: 5 | environment: 6 | - ASPNETCORE_ENVIRONMENT=Development 7 | - ASPNETCORE_URLS=https://+:443;http://+:80 8 | ports: 9 | - "80" 10 | - "443" 11 | volumes: 12 | - ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro 13 | - ${APPDATA}/ASP.NET/Https:/root/.aspnet/https:ro -------------------------------------------------------------------------------- /CQRS_Validation_FluentValidator/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.4' 2 | 3 | services: 4 | codemaze.web: 5 | image: ${DOCKER_REGISTRY-}web 6 | container_name: codemaze_web 7 | build: 8 | context: . 9 | dockerfile: Web/Dockerfile 10 | ports: 11 | - 5000:80 12 | - 5001:443 13 | depends_on: 14 | - codemaze.db 15 | 16 | codemaze.db: 17 | image: postgres:13.2 18 | container_name: codemaze_db 19 | environment: 20 | - POSTGRES_DB=users 21 | - POSTGRES_USER=postgres 22 | - POSTGRES_PASSWORD=postgres 23 | volumes: 24 | - ./db:/var/lib/postgresql/data 25 | ports: 26 | - 5432:5432 -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Code Maze 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CQRS Validation Pipeline with MediatR and FluentValidation 2 | ## https://code-maze.com/cqrs-mediatr-fluentvalidation 3 |

In this article, we are going to show you how to elegantly integrate a validation pipeline into our project using the MediatR and FluentValidation libraries.

4 |

This article is divided into the following sections:

5 |
    6 |
  • What is CQRS?
  • 7 |
  • Commands and Queries With MediatR
  • 8 |
  • Validation with FluentValidation
  • 9 |
  • Creating Decorators With MediatR PipelineBehavior
  • 10 |
  • Creating a Validation PipelineBehavior
  • 11 |
  • Handling Validation Exceptions
  • 12 |
  • Setting up Dependency Injection
  • 13 |
  • Validation Pipeline in Practice
  • 14 |
  • Conclusion
  • 15 |
16 | --------------------------------------------------------------------------------