qs.LibPack.UseCases
8.1.0
dotnet add package qs.LibPack.UseCases --version 8.1.0
NuGet\Install-Package qs.LibPack.UseCases -Version 8.1.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="qs.LibPack.UseCases" Version="8.1.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="qs.LibPack.UseCases" Version="8.1.0" />
<PackageReference Include="qs.LibPack.UseCases" />
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add qs.LibPack.UseCases --version 8.1.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: qs.LibPack.UseCases, 8.1.0"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package qs.LibPack.UseCases@8.1.0
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=qs.LibPack.UseCases&version=8.1.0
#tool nuget:?package=qs.LibPack.UseCases&version=8.1.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
qsLibPack.UseCases
Abstrações para implementação de Use Cases seguindo Clean Architecture, com Requests/Handlers, Dispatcher e Pipeline Behaviors (validação, exceção e unidade de trabalho).
Instalação
dotnet add package qs.LibPack.UseCases --version 8.1.0
Exemplos
Básico
Query retornando DTO com Response<T>.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using qsLibPack.UseCases.Abstractions;
using qsLibPack.UseCases.IoC;
using qsLibPack.UseCases.Models;
public sealed class GetUserByIdQuery : IQuery<Response<UserDto>>
{
public long Id { get; init; }
}
public sealed class GetUserByIdHandler : IUseCaseHandler<GetUserByIdQuery, Response<UserDto>>
{
private readonly IUserReadRepository repo;
public GetUserByIdHandler(IUserReadRepository repo) => this.repo = repo;
public async Task<Response<UserDto>> Handle(GetUserByIdQuery request, CancellationToken ct)
{
var user = await repo.GetByIdAsync(request.Id, ct);
return user is null
? Response<UserDto>.Fail(new[] { new qsLibPack.Validations.ErrorValidation("NotFound", "Usuário não encontrado") })
: Response<UserDto>.Ok(new UserDto(user.Id, user.Name, user.Email));
}
}
public record UserDto(long Id, string Name, string Email);
var services = new ServiceCollection();
services.AddUseCases(typeof(GetUserByIdHandler).Assembly);
var provider = services.BuildServiceProvider();
var dispatcher = provider.GetRequiredService<IUseCaseDispatcher>();
var result = await dispatcher.Send(new GetUserByIdQuery { Id = 1 });
Intermediário
Comando com validação FluentValidation e commit automático via UnitOfWorkBehavior.
using System.Threading;
using System.Threading.Tasks;
using FluentValidation;
using Microsoft.Extensions.DependencyInjection;
using qsLibPack.UseCases.Abstractions;
using qsLibPack.UseCases.IoC;
using qsLibPack.UseCases.Models;
public sealed class CreateUserCommand : ICommand<Response>
{
public string Name { get; init; } = string.Empty;
public string Email { get; init; } = string.Empty;
}
public sealed class CreateUserValidator : AbstractValidator<CreateUserCommand>
{
public CreateUserValidator()
{
RuleFor(x => x.Name).NotEmpty().WithErrorCode("Name");
RuleFor(x => x.Email).NotEmpty().EmailAddress().WithErrorCode("Email");
}
}
public sealed class CreateUserHandler : IUseCaseHandler<CreateUserCommand, Response>
{
private readonly IUserRepository repo;
public CreateUserHandler(IUserRepository repo) => this.repo = repo;
public async Task<Response> Handle(CreateUserCommand request, CancellationToken ct)
{
await repo.AddAsync(new User { Name = request.Name, Email = request.Email }, ct);
return Response.Ok();
}
}
var services = new ServiceCollection();
services.AddLogging();
services.AddUseCases(typeof(CreateUserHandler).Assembly);
services.AddScoped<qsLibPack.Repositories.Interfaces.IUnitOfWork, MyUnitOfWork>();
var provider = services.BuildServiceProvider();
var dispatcher = provider.GetRequiredService<IUseCaseDispatcher>();
var response = await dispatcher.Send(new CreateUserCommand { Name = "Alice", Email = "alice@acme.com" });
Avançado
Behavior customizado para auditoria e exceções centralizadas.
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using qsLibPack.UseCases.Abstractions;
using qsLibPack.UseCases.IoC;
public sealed class AuditBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
public async Task<TResponse> Handle(TRequest request, CancellationToken ct, Func<Task<TResponse>> next)
{
var sw = Stopwatch.StartNew();
var result = await next();
sw.Stop();
Console.WriteLine($"{typeof(TRequest).Name} -> {sw.ElapsedMilliseconds}ms");
return result;
}
}
var services = new ServiceCollection();
services.AddLogging();
services.AddUseCases(typeof(SomeHandler).Assembly);
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(AuditBehavior<,>));
Informações do NuGet
- Versão atual: 8.1.0
- Dependências:
- Microsoft.Extensions.DependencyInjection 8.*
- Microsoft.Extensions.Logging.Abstractions 8.*
- FluentValidation 12.1.0
- Compatibilidade: .NET 8 (net8.0)
- Link direto: https://www.nuget.org/packages/qs.LibPack.UseCases/
- Histórico (resumo):
- 8.0.0: estabilização dos behaviors,
ResponseeDispatchercom net8.0 - 8.1.0:
Dispatcherreescrito semMethodInfo.Invoke(wrapper genérico fortemente tipado, cache por tipo de request) — exceções do handler propagam com stack original;Response.Ok()sem alocações desnecessárias; fast path de validador único noValidationBehavior;UnitOfWorkBehaviornão faz commit quandoIResponse.Success == false
- 8.0.0: estabilização dos behaviors,
Como Contribuir
- Inclua exemplos de Requests/Handlers e behaviors com testes
- Utilize versionamento semântico e mantenha APIs estáveis
- Valide integração com DI e logging
Links
- Repositório: https://github.com/danilodumba/qsLibPack
- Documentação relacionada: qsLibPack
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net8.0
- FluentValidation (>= 12.1.0)
- Microsoft.Extensions.DependencyInjection (>= 8.0.1)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.3)
- qs.LibPack (>= 8.1.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.