13. Integrating Fluent Validation in .NET with Dependency Injection in Minimal API
Step 1: Create a New .NET Project Create a new .NET project if you don't already have one. You can use the following command to create a new web API project:
dotnet new webapi -n MagicVilla_CouponAPI
cd MagicVilla_CouponAPI
Step 2: Add Necessary NuGet Packages Add the FluentValidation package along with its Dependency Injection extensions:
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.1.0" />
You can add this line to your .csproj file or use the dotnet add package command:
dotnet add package FluentValidation.DependencyInjectionExtensions --version 11.1.0
Step 3: Create the Validation Class Create a folder named Validations and add a new class CouponCreateValidation for validating your CouponCreateDTO model.
using FluentValidation;
namespace MagicVilla_CouponAPI.Validations
{
public class CouponCreateValidation : AbstractValidator<CouponCreateDTO>
{
public CouponCreateValidation()
{
RuleFor(model => model.Name).NotEmpty();
RuleFor(model => model.Percent).InclusiveBetween(1, 100);
}
}
}
Step 4: Register FluentValidation in the Service Container Open the Program.cs file and register the FluentValidation services in the DI container.
using FluentValidation;
using FluentValidation.AspNetCore;
using MagicVilla_CouponAPI.Validations;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Register FluentValidation
builder.Services.AddValidatorsFromAssemblyContaining<CouponCreateValidation>();
var app = builder.Build();
// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Step 5: Create API Endpoints Next, create your API endpoints in Program.cs. Here is how you can set up a GET and POST endpoint for handling coupon operations:
app.MapGet("/api/coupon/{id:int}", (ILogger<Program> _logger, int id) => {
// Retrieve the coupon by id logic here
// For demonstration, assume we have a CouponStore class that stores coupons
var coupon = CouponStore.couponList.FirstOrDefault(c => c.Id == id);
if (coupon == null)
{
return Results.NotFound("Coupon not found");
}
return Results.Ok(coupon);
}).WithName("GetCoupon");
app.MapPost("/api/coupon", async (IMapper _mapper,
IValidator<CouponCreateDTO> _validation, [FromBody] CouponCreateDTO coupon_C_DTO) => {
var validationResult = await _validation.ValidateAsync(coupon_C_DTO);
if (!validationResult.IsValid)
{
return Results.BadRequest(validationResult.Errors.FirstOrDefault().ToString());
}
if (CouponStore.couponList.FirstOrDefault(u => u.Name.ToLower() == coupon_C_DTO.Name.ToLower()) != null)
{
return Results.BadRequest("Coupon Name already exists");
}
var coupon = _mapper.Map<Coupon>(coupon_C_DTO);
coupon.Id = CouponStore.couponList.OrderByDescending(u => u.Id).FirstOrDefault().Id + 1;
CouponStore.couponList.Add(coupon);
var couponDTO = _mapper.Map<CouponDTO>(coupon);
return Results.CreatedAtRoute("GetCoupon", new { id = coupon.Id }, couponDTO);
}).WithName("CreateCoupon").Accepts<CouponCreateDTO>("application/json").Produces<CouponDTO>(201).Produces(400);
Conclusion By following these steps, you have successfully integrated FluentValidation into your .NET project using Dependency Injection. This setup not only ensures your data is validated efficiently but also keeps your code clean and maintainable.
Feel free to extend these examples to fit the specific needs of your application, and enjoy the powerful validation capabilities provided by FluentValidation!