Introduction
In modern C# applications, clean architecture plays a crucial role in
maintaining scalability and maintainability. In this blog, we will build a
C# Web API using Onion Architecture,
CQRS, MediatR, and
Quartz.NET for scheduling background jobs. This guide will
walk you through structuring a project with
best practices and SOLID principles.
Why Use Onion Architecture?
Onion Architecture provides a clear separation of concerns by organizing the
application into different layers:
-
Domain Layer → Contains core business logic and entities
-
Application Layer → Contains CQRS commands, queries, and
interfaces
-
Infrastructure Layer → Handles database, repository
pattern, and external integrations
-
Presentation Layer (API Layer) → Exposes the application
as an API
Tech Stack
-
ASP.NET Core Web API for building RESTful APIs
-
Entity Framework Core for database operations
-
CQRS Pattern for separating read & write operations
-
MediatR for in-memory messaging
-
Quartz.NET for CRON Job scheduling
-
SOLID Principles to make the application scalable
๐ Project Structure
Your project will be structured as follows:
Step 1: Create the Student Model (Domain Layer)
๐ Location:
Onion.Domain/Models/Student.cs
Step 2: Create CQRS Commands & Queries (Application Layer)
✅ Command to Create a Student
๐ Location:
Onion.Application/Features/Students/Commands/CreateStudentCommand.cs
✅ Query to Get All Students
๐ Location:
Onion.Application/Features/Students/Queries/GetAllStudentsQuery.cs
Step 3: Implement Repository (Infrastructure Layer)
๐ Location:
Onion.Infrastructure/Repositories/StudentRepository.cs
Step 4: Implement CRON Job Using Quartz.NET
๐ Location:
Onion.Infrastructure/Scheduler/CronJobService.cs
Step 5: Register Everything in Program.cs
(API Layer)
๐ Location: Onion.API/Program.cs
Conclusion
By following this guide, you have successfully built a
C# Web API with Onion Architecture,
CQRS, MediatR, and
Quartz.NET CRON Jobs.
This approach ensures:
✅Scalability using Onion Architecture
✅Separation of Concerns (SoC)
✅Background Job Execution with Quartz.NET
✅Better Maintainability with CQRS & MediatR
๐ Download Full Project
Github