Thursday, March 6, 2025

Building a C# Web API with Onion Architecture, CQRS, MediatR & Quartz.NET CRON Jobs

 


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:

  1. Domain Layer → Contains core business logic and entities

  2. Application Layer → Contains CQRS commands, queries, and interfaces

  3. Infrastructure Layer → Handles database, repository pattern, and external integrations

  4. 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:

    Architecture Snippet

    Step 1: Create the Student Model (Domain Layer)

    ๐Ÿ“ Location: Onion.Domain/Models/Student.cs

    Model Snippet

    Step 2: Create CQRS Commands & Queries (Application Layer)

    ✅ Command to Create a Student

    ๐Ÿ“ Location: Onion.Application/Features/Students/Commands/CreateStudentCommand.cs

    Code Snippet

    ✅ Query to Get All Students

    ๐Ÿ“ Location: Onion.Application/Features/Students/Queries/GetAllStudentsQuery.cs

    Code Snippet

    Step 3: Implement Repository (Infrastructure Layer)

    ๐Ÿ“ Location: Onion.Infrastructure/Repositories/StudentRepository.cs

    Code Snippet

    Step 4: Implement CRON Job Using Quartz.NET

    ๐Ÿ“ Location: Onion.Infrastructure/Scheduler/CronJobService.cs

    Code Snippet

    Step 5: Register Everything in Program.cs (API Layer)

    ๐Ÿ“ Location: Onion.API/Program.cs

    Code Snippet

    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

No comments:

Post a Comment

How to Do Cross-Browser Testing on Windows — Including Safari via Playwright

To test follow few steps: Step 1. Install node Step 2. create Folder and run these commands commands Copy Code ...