CleanCodeJN.GenericApis
4.1.4
dotnet add package CleanCodeJN.GenericApis --version 4.1.4
NuGet\Install-Package CleanCodeJN.GenericApis -Version 4.1.4
<PackageReference Include="CleanCodeJN.GenericApis" Version="4.1.4" />
<PackageVersion Include="CleanCodeJN.GenericApis" Version="4.1.4" />
<PackageReference Include="CleanCodeJN.GenericApis" />
paket add CleanCodeJN.GenericApis --version 4.1.4
#r "nuget: CleanCodeJN.GenericApis, 4.1.4"
#addin nuget:?package=CleanCodeJN.GenericApis&version=4.1.4
#tool nuget:?package=CleanCodeJN.GenericApis&version=4.1.4
๐ Generic Web APIs โ Fast, Clean, Powerful
Create clean and testable web APIs in seconds โ from simple CRUD to fully structured IOSP-based architectures โ powered by the Mediator pattern, AutoMapper, FluentValidation and Entity Framework, all wired together with Clean Code principles.
This package gives you:
- โ blazing-fast setup
- โ CRUD APIs in seconds without writing a single line of code
- โ complex business logic with IOSP
- โ testable architecture
- โ maintainable and modular code
๐งช What is IOSP?
Integration Operation Segregation Principle
Split your request handlers into: Operations โ contain real logic (DB, API, etc.)
Integrations โ just orchestrate other request handlers
โจ Features at a Glance
- โก Plug & Play CRUD APIs (Minimal API or Controller-based)
- ๐ฆ Built-in paging, filtering & projections
- ๐ง Clean separation of logic using the Mediator pattern
- ๐งฑ Entity Framework abstraction via
DataRepositories
- ๐ Auto-mapping of Entities โ DTOs (no config needed)
- ๐งช Fluent validation out of the box
- ๐งผ CleanCode-first architecture using the IOSP Principle
- ๐งช Easily mockable and testable
- ๐ Runs on .NET 9
How to use
- Add AddCleanCodeJN<IDataContext>() to your Program.cs
- Add app.UseCleanCodeJNWithMinimalApis() to your Program.cs for minimal APIs or use AddControllers + MapControllers()
- Start writing Apis by implementing IApi
- Extend standard CRUD operations by specific Where() and Include() clauses
- Use IOSP for complex business logic
Step by step explanation
Add AddCleanCodeJN<IDataContext>() to your Program.cs
builder.Services.AddCleanCodeJN<MyDbContext>(options => {});
- All Entity โ DTO Mappings will be done automatically if the naming Convention will be applied: e.g.: Customer โ CustomerGetDto.
- DTO has to start with Entity-Name and must inherits from IDto
- Entity must inherit from IEntity
These are the CleanCodeJN Options
/// <summary>
/// The options for the CleanCodeJN.GenericApis
/// </summary>
public class CleanCodeOptions
{
/// <summary>
/// The assemblies that contain the command types, Entity types and DTO types for automatic registration of commands, DTOs and entities.
/// </summary>
public List<Assembly> ApplicationAssemblies { get; set; } = [];
/// <summary>
/// The assembly that contains the validators types for using Fluent Validation.
/// </summary>
public Assembly ValidatorAssembly { get; set; }
/// <summary>
/// The assembly that contains the automapper mapping profiles.
/// </summary>
public Action<IMapperConfigurationExpression> MappingOverrides { get; set; }
/// <summary>
/// If true: Use distributed memory cache. If false: you can add another Distributed Cache implementation.
/// </summary>
public bool UseDistributedMemoryCache { get; set; } = true;
/// <summary>
/// If true: Add default logging behavior. If false: you can add another logging behavior.
/// </summary>
public bool AddDefaultLoggingBehavior { get; set; }
/// <summary>
/// Mediatr Types of Open Behaviors to register
/// </summary>
public List<Type> OpenBehaviors { get; set; } = [];
/// <summary>
/// Mediatr Types of Closed Behaviors to register
/// </summary>
public List<Type> ClosedBehaviors { get; set; } = [];
}
Add app.UseCleanCodeJNWithMinimalApis() when using Minimal APIs to your Program.cs
app.UseCleanCodeJNWithMinimalApis();
When using Controllers add this to your Program.cs
builder.Services.AddControllers()
.AddNewtonsoftJson(); // this is needed for "http patch" only. If you do not need to use patch, you can remove this line
// After Build()
app.MapControllers();
Start writing Minimal Apis by implementing IApi
public class CustomersV1Api : IApi
{
public List<string> Tags => ["Customers Minimal API"];
public string Route => $"api/v1/Customers";
public List<Func<WebApplication, RouteHandlerBuilder>> HttpMethods =>
[
app => app.MapGet<Customer, CustomerGetDto, int>(
Route,
Tags,
where: x => x.Name.StartsWith("Customer"),
includes: [x => x.Invoices],
select: x => new Customer { Name = x.Name },
ignoreQueryFilters: true),
app => app.MapGetPaged<Customer, CustomerGetDto, int>(Route, Tags),
app => app.MapGetFiltered<Customer, CustomerGetDto, int>(Route, Tags),
app => app.MapGetById<Customer, CustomerGetDto, int>(Route, Tags),
app => app.MapPut<Customer, CustomerPutDto, CustomerGetDto>(Route, Tags),
app => app.MapPost<Customer, CustomerPostDto, CustomerGetDto>(Route, Tags),
app => app.MapPatch<Customer, CustomerGetDto, int>(Route, Tags),
// Or use a custom Command with MapDeleteRequest()
app => app.MapDeleteRequest<Customer, CustomerGetDto, int>(Route, Tags, id => new DeleteCustomerIntegrationRequest { Id = id })
];
}
Extend standard CRUD operations by specific Where(), Include() or Select() clauses
public class CustomersV1Api : IApi
{
public List<string> Tags => ["Customers Minimal API"];
public string Route => $"api/v1/Customers";
public List<Func<WebApplication, RouteHandlerBuilder>> HttpMethods =>
[
app => app.MapGet<Customer, CustomerGetDto, int>(Route, Tags, where: x => x.Name.StartsWith("a"), select: x => new Customer { Name = x.Name }),
];
}
Or use ApiCrudControllerBase for CRUD operations in controllers
[Tags("Customers Controller based")]
[Route($"api/v2/[controller]")]
public class CustomersController(IMediator commandBus, IMapper mapper)
: ApiCrudControllerBase<Customer, CustomerGetDto, CustomerPostDto, CustomerPutDto, int>(commandBus, mapper)
{
}
You can also override your Where, Include or Select clauses
/// <summary>
/// Customers Controller based
/// </summary>
/// <param name="commandBus">IMediatr instance.</param>
/// <param name="mapper">Automapper instance.</param>
[Tags("Customers Controller based")]
[Route($"api/v2/[controller]")]
public class CustomersController(IMediator commandBus, IMapper mapper)
: ApiCrudControllerBase<Customer, CustomerGetDto, CustomerPostDto, CustomerPutDto, int>(commandBus, mapper)
{
/// <summary>
/// Where clause for the Get method.
/// </summary>
public override Expression<Func<Customer, bool>> GetWhere => x => x.Name.StartsWith("Customer");
/// <summary>
/// Includes for the Get method.
/// </summary>
public override List<Expression<Func<Customer, object>>> GetIncludes => [x => x.Invoices];
/// <summary>
/// Select for the Get method.
/// </summary>
public override Expression<Func<Customer, Customer>> GetSelect => x => new Customer { Id = x.Id, Name = x.Name };
/// <summary>
/// AsNoTracking for the Get method.
/// </summary>
public override bool AsNoTracking => true;
}
For using the /filtered api with a filter, just provide a serialized json as filter parameter, like this:
{
"Condition" : 0, // 0 = AND; 1 = OR
"Filters": [
{
"Field": "Name",
"Value": "aac",
"Type": 0
},
{
"Field": "Id",
"Value": "3",
"Type": 1
}
]
}
Which means: Give me all Names which CONTAINS "aac" AND have Id EQUALS 3. So string Types use always CONTAINS and integer types use EQUALS. All filters are combined with ANDs.
The Type can be specified with these values:
public enum FilterTypeEnum
{
STRING = 0,
INTEGER = 1,
DOUBLE = 2,
INTEGER_NULLABLE = 3,
DOUBLE_NULLABLE = 4,
DATETIME = 5,
DATETIME_NULLABLE = 6,
GUID = 7,
GUID_NULLABLE = 8,
}
Advanced Topics
Built-in Support for Fluent Validation:
Just write your AbstractValidators<T>. They will be automatically executed on generic POST and generic PUT actions:
public class CustomerPostDtoValidator : AbstractValidator<CustomerPostDto>
{
public CustomerPostDtoValidator()
{
RuleFor(x => x.Name)
.NotEmpty()
.MaximumLength(10);
}
public class CustomerPutDtoValidator : AbstractValidator<CustomerPutDto>
{
public CustomerPutDtoValidator()
{
RuleFor(x => x.Id)
.GreaterThan(0);
RuleFor(x => x.Name)
.NotEmpty()
.MaximumLength(10)
.CreditCard();
}
}
Implement your own specific Request:
public class SpecificDeleteRequest : IRequest<BaseResponse<Customer>>
{
public required int Id { get; init; }
}
Requests can also be marked as ICachableRequest, which uses IDistributedCache to cache the Response:
public class SpecificDeleteRequest : IRequest<BaseResponse<Customer>>, ICachableRequest
{
public required int Id { get; init; }
public bool BypassCache { get; }
public string CacheKey => "Your Key";
public TimeSpan? CacheDuration => TimeSpan.FromHours(168);
}
With your own specific Command using CleanCodeJN.Repository
public class SpecificDeleteCommand(IRepository<Customer, int> repository) : IRequestHandler<SpecificDeleteRequest, BaseResponse<Customer>>
{
public async Task<BaseResponse<Customer>> Handle(SpecificDeleteRequest request, CancellationToken cancellationToken)
{
var deletedCustomer = await repository.Delete(request.Id, cancellationToken);
return await BaseResponse<Customer>.Create(deletedCustomer is not null, deletedCustomer);
}
}
Use IOSP for complex business logic
Derive from BaseIntegrationCommand:
public class YourIntegrationCommand(ICommandExecutionContext executionContext)
: IntegrationCommand<YourIntegrationRequest, YourDomainObject>(executionContext)
Write Extensions on ICommandExecutionContext with Built in Requests or with your own
public static ICommandExecutionContext CustomerGetByIdRequest(
this ICommandExecutionContext executionContext, int customerId)
=> executionContext.WithRequest(
() => new GetByIdRequest<Customer>
{
Id = customerId,
Includes = [x => x.Invoices, x => x.OtherDependentTable],
},
CommandConstants.CustomerGetById);
See the how clean your code will look like in the end
public class YourIntegrationCommand(ICommandExecutionContext executionContext)
: IntegrationCommand<YourIntegrationRequest, Customer>(executionContext)
{
public override async Task<BaseResponse<Customer>> Handle(YourIntegrationRequest request, CancellationToken cancellationToken) =>
await ExecutionContext
.CandidateGetByIdRequest(request.Dto.CandidateId)
.CustomerGetByIdRequest(request.Dto.CustomerIds)
.GetOtherStuffRequest(request.Dto.XYZType)
.PostSomethingRequest(request.Dto)
.SendMailRequest()
.Execute<Customer>(cancellationToken);
}
Sample Code
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net9.0 is compatible. 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. |
-
net9.0
- AutoMapper (>= 14.0.0)
- CleanCodeJN.GenericApis.Abstractions (>= 3.0.0)
- CleanCodeJN.Repository.EntityFramework (>= 2.0.0)
- FluentValidation (>= 11.11.0)
- FluentValidation.AspNetCore (>= 11.3.0)
- MediatR (>= 12.4.1)
- Microsoft.AspNetCore.JsonPatch (>= 9.0.3)
- Microsoft.Extensions.Caching.Memory (>= 9.0.3)
- Newtonsoft.Json (>= 13.0.3)
- System.Formats.Asn1 (>= 9.0.3)
- System.Text.Json (>= 9.0.3)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on CleanCodeJN.GenericApis:
Package | Downloads |
---|---|
CleanCodeJN.GenericApis.ServiceBusConsumer
This CleanCodeJN package for Service Bus simplifies the development of asynchronous microservices by providing a framework that leverages the power of MediatR and IOSP to consume service bus events from topics and execute commands to process these events. |
GitHub repositories
This package is not used by any popular GitHub repositories.
Version | Downloads | Last updated |
---|---|---|
4.1.4 | 121 | 4/3/2025 |
4.1.3 | 114 | 4/2/2025 |
4.1.2 | 114 | 4/2/2025 |
4.1.1 | 104 | 3/28/2025 |
4.1.0 | 104 | 3/28/2025 |
4.0.3 | 110 | 3/27/2025 |
4.0.2 | 108 | 3/27/2025 |
4.0.1 | 459 | 3/25/2025 |
4.0.0 | 101 | 2/28/2025 |
3.6.1 | 110 | 2/7/2025 |
3.6.0 | 170 | 12/12/2024 |
3.5.1 | 108 | 12/7/2024 |
3.5.0 | 115 | 11/19/2024 |
3.4.1 | 123 | 11/10/2024 |
3.4.0 | 111 | 11/10/2024 |
3.3.0 | 132 | 10/21/2024 |
3.2.2 | 134 | 10/20/2024 |
3.2.1 | 135 | 10/20/2024 |
3.2.0 | 129 | 10/20/2024 |
3.1.9 | 155 | 10/18/2024 |
3.1.8 | 121 | 10/9/2024 |
3.1.7 | 104 | 10/8/2024 |
3.1.6 | 112 | 10/8/2024 |
3.1.5 | 117 | 9/25/2024 |
3.1.4 | 135 | 9/12/2024 |
3.1.3 | 113 | 9/12/2024 |
3.1.2 | 110 | 9/12/2024 |
3.1.1 | 126 | 9/11/2024 |
3.1.0 | 108 | 9/9/2024 |
3.0.4 | 108 | 9/6/2024 |
3.0.3 | 111 | 9/6/2024 |
3.0.2 | 124 | 9/3/2024 |
3.0.1 | 90 | 7/30/2024 |
3.0.0 | 146 | 5/24/2024 |
2.2.0 | 117 | 5/23/2024 |
2.1.1 | 119 | 5/22/2024 |
2.1.0 | 123 | 5/15/2024 |
2.0.8 | 107 | 5/14/2024 |
2.0.7 | 118 | 5/14/2024 |
2.0.6 | 106 | 5/14/2024 |
2.0.5 | 109 | 5/13/2024 |
2.0.4 | 97 | 5/13/2024 |
2.0.3 | 102 | 5/12/2024 |
2.0.2 | 110 | 5/11/2024 |
2.0.1 | 113 | 5/8/2024 |
2.0.0 | 127 | 5/7/2024 |
1.1.1 | 124 | 5/7/2024 |
1.1.0 | 118 | 5/7/2024 |
1.0.6 | 139 | 5/7/2024 |
1.0.5 | 121 | 5/7/2024 |
1.0.4 | 123 | 5/7/2024 |
1.0.3 | 145 | 5/7/2024 |
1.0.2 | 119 | 5/6/2024 |
1.0.1 | 128 | 5/6/2024 |
1.0.0 | 127 | 5/6/2024 |
Important README.md updates.