
<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Design Pattern Architecture &#8211; CodeInDotNet</title>
	<atom:link href="https://www.codeindotnet.com/category/design-pattern-architecture/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.codeindotnet.com</link>
	<description>C# Dot Net Programming tutorial &#38; code examples</description>
	<lastBuildDate>Thu, 05 Sep 2024 03:35:32 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>

<image>
	<url>https://www.codeindotnet.com/wp-content/uploads/2021/04/SiteIcon.png</url>
	<title>Design Pattern Architecture &#8211; CodeInDotNet</title>
	<link>https://www.codeindotnet.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Vertical Slice Architecture</title>
		<link>https://www.codeindotnet.com/vertical-slice-architecture/</link>
					<comments>https://www.codeindotnet.com/vertical-slice-architecture/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 05 Sep 2024 03:34:33 +0000</pubDate>
				<category><![CDATA[Design Pattern Architecture]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=9991</guid>

					<description><![CDATA[Vertical Slice Architecture Layered architectures are the base of many software systems, but they group the system by technical layers, which don&#8217;t always work closely together. What if you wanted to organize the system around features and ensure all parts of a single feature are closely linked? In this article, we will discuss Vertical Slice [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div id="PageInHoriAd1"></div>
<script>
fetch('/gads/PageInHoriAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInHoriAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInHoriAd1:', error);
	});
</script>
<br>



<h2 class="wp-block-heading h2Cust1" id="vertical-slice-architecture"><strong>Vertical Slice Architecture</strong></h2>



<br>



<p>Layered architectures are the base of many software systems, but they group the system by technical layers, which don&#8217;t always work closely together. What if you wanted to organize the system around features and ensure all parts of a single feature are closely linked? In this article, we will discuss Vertical Slice Architecture, which does exactly that organizing the system around features.</p>



<br>



<h3 class="wp-block-heading hLBRed" id="drawback-of-layered-architecture"><strong>Drawback of Layered Architecture</strong></h3>



<p class="custp1">Layered architectures split the software into different layers or tiers, with each layer often being its own project for example N-tier and Clean architecture. This approach makes the system easier to understand and maintain, offering benefits like maintainability, flexibility, and loose coupling.</p>



<p class="custp1 p-mb-0">However, layered architectures can be restrictive because the dependencies between layers are fixed. For example, in Clean Architecture: </p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li>The domain has no dependencies</li>



<li>The application layer can reference the Domain</li>



<li>Infrastructure can reference both Applications</li>



<li>Domain and Presentation can reference both Application and Domain</li>
</ul>



<p class="custp1">This setup leads to high coupling within layers and low coupling between them, which increases complexity due to many abstractions that need to be maintained.</p>



<br>



<h3 class="wp-block-heading hLBRed" id="what-is-vertical-slice-architecture"><strong>What is Vertical Slice Architecture</strong></h3>



<p class="custp1">Vertical Slice Architecture is a design approach where a system is divided into vertical slices, each representing a feature or a specific functionality of the application. Unlike traditional layered architecture, where the system is split into horizontal layers (e.g., presentation, business logic, data access), vertical slices focus on delivering complete features from the UI down to the database.</p>



<p class="p-mb-0"><strong>Each slice in this architecture contains everything needed to implement a specific feature</strong>, including:</p>



<ul class="ol1 ol1-mb-0 wp-block-list">
<li>Controllers (or API endpoints)</li>



<li>Application logic</li>



<li>Domain logic (business rules)</li>



<li>Data access logic</li>
</ul>



<br>



<p>This approach promotes separation of concerns and allows for better scalability and maintainability. It also aligns with <a href="/domain-driven-design-ddd-approach/" data-type="post" data-id="7354" target="_blank" rel="noreferrer noopener"><strong>Domain-Driven Design (DDD)</strong></a> by focusing on the business domain.</p>



<p class="p-mb-0">Here’s an example of a folder structure in a .NET Core Web API project following the Vertical Slice Architecture.</p>



<pre class="pchl"><code>&#128193;-- Features/
	&#128193; -- <b>CreateOrder</b>/
		&#128193;-- CreateOrderRequest.cs
		&#128193; -- CreateOrderHandler.cs
		&#128193; -- CreateOrderResponse.cs
		&#128193; -- CreateOrderController.cs
	&#128193;-- <b>GetOrder</b>/
		&#128193; -- GetOrderRequest.cs
		&#128193; -- GetOrderHandler.cs
		&#128193; -- GetOrderResponse.cs
		&#128193; -- GetOrderController.cs </code></pre>



<p class="p-mb-0">Each vertical slice typically includes:</p>



<ul class="ol1 wp-block-list">
<li><strong>Request</strong>: A class representing the input data for the slice (e.g., a DTO).</li>



<li><strong>Handler</strong>: A class responsible for handling the request, containing the business logic.</li>



<li><strong>Response</strong>: A class representing the output data (e.g., a DTO or ViewModel).</li>



<li><strong>Controller</strong>: The API endpoint that interacts with the request and response classes.</li>
</ul>



<br>



<p class="p-mb-0">Here&#8217;s how you can visualize vertical slices:</p>



<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="456" height="421" src="https://www.codeindotnet.com/wp-content/uploads/2024/09/vertical-slice-architecture.jpg" alt="Vertical Slice Architecture" class="wp-image-10007" srcset="https://www.codeindotnet.com/wp-content/uploads/2024/09/vertical-slice-architecture.jpg 456w, https://www.codeindotnet.com/wp-content/uploads/2024/09/vertical-slice-architecture-300x277.jpg 300w" sizes="(max-width: 456px) 100vw, 456px" /></figure>



<br><br>



<h3 class="wp-block-heading hLBRed" id="benefits-of-vertical-slice-architecture"><strong>Benefits of Vertical Slice Architecture</strong></h3>



<ol class="ol1 ol1-mb-0 wp-block-list">
<li class="custp1"><strong>Feature Isolation</strong>: Each slice is self-contained, making it easier to understand and modify specific features without impacting the entire system.</li>



<li><strong>Scalability</strong>: As features are isolated, teams can work on different slices independently, enabling parallel development and deployment.</li>



<li><strong>Testability</strong>: Since each slice is independent, it&#8217;s easier to write and maintain unit and integration tests.</li>



<li><strong>Flexibility</strong>: You can use different technologies or patterns for different slices if needed, adapting to the specific needs of each feature.</li>
</ol>



<p class="custp1">The best part is you can remove or disable any feature at any time if it&#8217;s not needed. Simply exclude it from the project, build the application, and run it. This won&#8217;t cause any problems because the removed feature is not linked to any other feature, as all features are independent.</p>



<br>



<p class="brgrey"><strong>Read &#8211;</strong> <a href="/implementing-cqrs-mediator-pattern-web-api-aspnet-core/" target="_blank" rel="noreferrer noopener"><strong>CQRS implementation with Vertical Slice Architecture using Mediator</strong></a>. This article explains how to implement Vertical Slice Architecture in CQRS design pattern with Mediator using Mediatr library, in asp.net core Web API application.</p>



<div id="PageInAd1"></div>
<script>
fetch('/gads/PageInAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd1:', error);
	});
</script>



<br><br>
<script src="/my-js/latesttop10post.js" type="text/javascript"></script>
<input type="hidden" id="cids" value="191,3,59,71">
<div id="latestPostlist"></div>
<br><br>



<div class="wp-block-rank-math-toc-block toc-cust" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#vertical-slice-architecture">Vertical Slice Architecture</a><ul><li><a href="#drawback-of-layered-architecture">Drawback of Layered Architecture</a></li><li><a href="#what-is-vertical-slice-architecture">What is Vertical Slice Architecture</a></li><li><a href="#benefits-of-vertical-slice-architecture">Benefits of Vertical Slice Architecture</a></li></ul></li></ul></nav></div>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/vertical-slice-architecture/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Implementing CQRS and Mediator Design Patterns in Web API .Net 8</title>
		<link>https://www.codeindotnet.com/implementing-cqrs-mediator-pattern-web-api-aspnet-core/</link>
					<comments>https://www.codeindotnet.com/implementing-cqrs-mediator-pattern-web-api-aspnet-core/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 05 Sep 2024 03:11:20 +0000</pubDate>
				<category><![CDATA[Design Pattern Architecture]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=10014</guid>

					<description><![CDATA[What is CQRS? CQRS, short for Command Query Responsibility Segregation, is a design pattern that separates the application’s read and write operations into two parts &#8211; commands (write operations) and queries (read operations). This segregation allows for more flexible and scalable systems, particularly in complex applications or rapidly changing business requirements, where the read &#38; [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div id="PageInHoriAd1"></div>
<script>
fetch('/gads/PageInHoriAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInHoriAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInHoriAd1:', error);
	});
</script>
<br>



<h2 class="wp-block-heading hLBRed" id="what-is-cqrs"><strong>What is CQRS?</strong></h2>



<p class="custp1">CQRS, short for Command Query Responsibility Segregation, is a design pattern that separates the application’s read and write operations into two parts &#8211; <strong>commands</strong> (write operations) and <strong>queries</strong> (read operations). This segregation allows for more flexible and scalable systems, particularly in complex applications or rapidly changing business requirements, where the read &amp; write operations differ significantly.</p>



<p class="custp1 p-mb-0"><strong>1) Commands</strong> are actions that change the state of the system, by performing <span class="spanHT">Create()</span>, <span class="spanHT">Update()</span> and <span class="spanHT">Delete()</span> operations. </p>



<p class="custp1 p-mb-0">The command pattern consists of two objects:</p>



<ul class="ol1 wp-block-list">
<li><strong>Command</strong>&nbsp;– Defines which methods should be executed.</li>



<li><strong>Command Handler</strong>&nbsp;– responsible for processing commands, which are requests to perform actions that change the state of the system.</li>
</ul>



<p class="custp1 p-mb-0"><strong>2) Queries</strong> are actions that retrieve read-only data from the system without changing its state, for example, <span class="spanHT">Get()</span> operation. It doesn’t alter the data, just fetches it. </p>



<p class="custp1 p-mb-0">The query pattern consists of two objects:</p>



<ul class="ol1 wp-block-list">
<li><strong>Query</strong>&nbsp;– Defines the objects to be returned.</li>



<li><strong>Query Handler</strong>&nbsp;– responsible for processing queries, which are requests to retrieve data from the system.</li>
</ul>



<br>



<h2 class="wp-block-heading hLBRed" id="why-use-cqrs"><strong>Why Use CQRS?</strong></h2>



<p class="custp1 p-mb-0">It’s common to see traditional architectural patterns that use the same data model or DTO for querying and persisting data and handle a significant volume of read-and-write operations. This approach works well for simple CRUD operations, but as the number of users, the volume of these operations and the complexity of the system increases, the application may encounter performance, scalability, and flexibility challenges.</p>



<p class="custp1 p-mb-0">The primary goal of CQRS is to use different data models effectively, providing flexibility in scenarios that require a complex structure. It allows you to create multiple DTOs without breaking architectural principles or risking data loss. </p>



<p class="custp1">You can implement CQRS using Mediator (MediatR library) in .Net.</p>



<br>



<h2 class="wp-block-heading hLBRed" id="what-is-mediator"><strong>What is Mediator?</strong></h2>



<p class="custp1 p-mb-0">The <strong>Mediator</strong> is a behavioral design pattern that facilitates communication between different components or objects in a system by centralizing this interaction through a mediator object. Instead of components communicating directly with each other, which can lead to a tightly coupled and complex system, they interact with the mediator, which handles the communication and coordination between them. </p>



<p class="custp1 p-mb-0">In short, Mediator makes a bridge between different objects, which eliminates the dependency between them as they do not communicate directly.</p>



<p class="custp1 p-mb-0">In .NET Core, the <strong>Mediator</strong> pattern is often implemented using the <span class="spanHT">MediatR</span> library, which is a popular library for implementing this pattern. When using <strong>MediatR</strong>, you create a request (like a command or query) and a corresponding handler. The request is sent to the mediator, which then routes the requests to their respective handlers.</p>



<p class="custp1 p-mb-0"><strong>Pros:</strong> Independence between different objects, Centralized communication, and Easy maintenance.</p>



<p class="custp1"><strong>Cons:</strong> Greater complexity, and it can become a bottleneck in an application if it has to handle a large amount of data.</p>



<br><br>



<h2 class="wp-block-heading h2Cust1" id="cqrs-and-mediator-implementation"><strong>CQRS and Mediator Implementation</strong></h2>



<br>



<p>Let&#8217;s create a simple Web API project and understand the basic implementation of CQRS design pattern using MediatR library, step-by-step. </p>



<p><strong>1) Create a new ASP.NET Core Web API project</strong> in Visual Studio.</p>



<p><strong>2) Add project Dependencies</strong> in .csproj file or via NuGet package manager.</p>



<pre class="pchl"><code>&lt;PackageReference Include=<span class="str">"MediatR"</span> Version=<span class="str">"12.4.0"</span> /&gt
&lt;PackageReference Include=<span class="str">"Microsoft.EntityFrameworkCore"</span> Version=<span class="str">"8.0.8"</span> /&gt
&lt;PackageReference Include=<span class="str">"Microsoft.EntityFrameworkCore.SqlServer"</span> Version=<span class="str">"8.0.8"</span> /&gt
&lt;PackageReference Include=<span class="str">"Microsoft.EntityFrameworkCore.Tools"</span> Version=<span class="str">"8.0.8"</span>&gt </code></pre>



<br><br>



<p><strong>3) Create the Entity Model:</strong> For demonstration purposes, create a Model class called &#8220;<strong>EmployeeModel</strong>&#8221; and add these 5 fields &#8211; <strong>Id</strong>(primary key), <strong>Name</strong>, <strong>Gender</strong>, <strong>RoldId</strong>, <strong>EmailId</strong>. This entity model will be passed to Entity Framework to make database changes.</p>



<p class="custp1"><strong>4) Create DTO</strong> (Data Transfer Object) for &#8220;EmployeeModel&#8221; model, and name that class as &#8220;<strong>EmployeeDTO</strong>&#8220;. DTOs usually include only the data required by the client, excluding any unnecessary or sensitive information.</p>



<p class="custp1"><strong>5) Create the Database Context:</strong> Add new class called &#8220;ApplicationDbContext&#8221; and add the following code:</p>



<pre class="pchl"><code><span class="key">using</span> Microsoft.EntityFrameworkCore;

<span class="key">namespace</span> Infrastructure;

<span class="key">public</span> <span class="key">sealed</span> <span class="key">class</span> ApplicationDbContext : DbContext
{
    <span class="key">public</span> ApplicationDbContext(DbContextOptions&lt;ApplicationDbContext&gt options)
        : <span class="key">base</span>(options)
    {
    }

    <span class="key">public</span> <span class="custkey">DbSet</span>&lt;<b>EmployeeModel</b>&gt Employees { get; set; }
} </code></pre>



<br><br>



<p class="p-mb-0"><strong>6) Add required services</strong> to the Program.cs file.</p>



<div style="padding-left: 0.9375rem;">
<p class="custp1 p-mb-0"><strong>a.</strong> Register Mediator service:</p>
<pre class="pchl" style="margin-top:0;"><code><span class="com">// Adding the MediatR dependency</span>
builder.Services.<span style="background:#f2f19d;">AddMediatR</span>(m=&gt m.RegisterServicesFromAssemblies(<span class="key">typeof</span>(Program).Assembly));</code></pre>
</div>



<br>



<div style="padding-left: 0.9375rem;">
<p class="p-mb-0"><strong>b.</strong> Add Database Context:</p>
<pre class="pchl" style="margin-top:0;"><code>builder.Services.<span style="background:#f2f19d;">AddDbContext</span>&lt;ApplicationDbContext&gt(options =&gt
        options.UseSqlServer(builder.Configuration.GetConnectionString(<span class="str">"DefaultConnection"</span>))
    ); </code></pre>
</div>



<br><br>



<p class="p-mb-0"><strong>7) Run EF Core Commands (Add-Migration)</strong></p>



<p class="custp1 p-mb-0"> You can run the following commands from the &#8216;Package Manager Console&#8217; in Visual Studio:</p>



<ul class="ol1 wp-block-list">
<li><strong>Add-Migration InitialModel</strong></li>



<li>Update-Database</li>
</ul>



<p class="p-mb-0">Alternatively, you can run the commands below in a project root terminal.</p>



<ul class="ol1 wp-block-list">
<li>dotnet ef migrations add InitialModel</li>



<li>dotnet ef database update</li>
</ul>



<br>



<p class="p-mb-0"><strong>8) Implement the CQRS design pattern</strong></p>



<p class="custp1 p-mb-0">We will follow the <strong><a href="/vertical-slice-architecture/" target="_blank" rel="noreferrer noopener nofollow">Vertical Slice Architecture</a></strong> approach to organize our folder structure by feature. </p>



<p class="custp1">Create a new folder called “Employee” under &#8220;Features&#8221; folder and inside it create two new folders “Commands” and “Queries.” </p>



<p>Inside the&nbsp;<strong>Commands&nbsp;</strong>and&nbsp;<strong>Queries&nbsp;</strong>folders, create a folder for each function you need to execute like Create, Read, Update, and Delete operations. See the folder structure below, organized by feature-wise.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://www.codeindotnet.com/wp-content/uploads/2024/09/cqrs-folder-structure.jpg" alt="CQRS and Mediator Design Patterns"/></figure>



<br><br>



<p class="p-mb-0"><strong>9) Create the Query/Command class</strong>: Create a Handler for each Query/Command class, follow the code given below:</p>



<h3 class="wp-block-heading custp1" id="create-queries"><strong>Create Queries</strong></h3>



<br>



<h4 class="wp-block-heading" id="a-get-all-employees"><strong>a. Get All Employees:</strong></h4>



<br>
<div style="padding-left: 0.9375rem;">
<div style="padding-bottom: 0.3125rem;"><b><i>Query:</i></b></div>
<pre class="pchl" style="margin-top:0;"><code><span class="key">public</span> <span class="key">sealed</span> record <span class="custkey">GetAllEmployeeQuery</span> : <span class="custkey">IRequest</span>&lt;List&lt;EmployeeDTO&gt&gt
{
} </code></pre>
</div>



<br>
<div style="padding-left: 0.9375rem;">
<div style="padding-bottom: 0.3125rem;"><b><i>Query Handler:</i></b></div>
<pre class="pchl" style="margin-top:0;"><code><span class="key">public</span> <span class="key">sealed</span> record <span class="custkey">GetAllEmployeeQueryHandler</span> : <span class="custkey">IRequestHandler</span>&lt;GetAllEmployeeQuery, List&lt;EmployeeDTO&gt&gt
{
    <span class="key">public</span> <span class="custkey">GetAllEmployeeQueryHandler</span>(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    <span class="key">private</span> <span class="key">readonly</span> ApplicationDbContext _dbContext;

    <span class="key">public</span> <span class="key">async</span> Task&lt;List&lt;EmployeeDTO&gt&gt Handle(GetAllEmployeeQuery request, CancellationToken cancellationToken)
    {
        <span class="key">return</span> <span class="key">await</span> _dbContext.Employees
            .AsNoTracking()
            .Select(s=&gt <span class="key">new</span> EmployeeDTO
            {
                Id = s.Id,
                Name = s.Name,
                EmailId = s.EmailId,
                Gender = s.Gender,
                RoleId = s.RoleId   
            })
            .ToListAsync(cancellationToken);
    }
} </code></pre>
</div>
<br><br>



<h4 class="wp-block-heading" id="b-get-employee-by-id"><strong>b. Get Employee By Id:</strong></h4>



<br>
<div style="padding-left: 0.9375rem;">
<div style="padding-bottom: 0.3125rem;"><b><i>Query:</i></b></div>
<pre class="pchl" style="margin-top:0;"><code><span class="key">public</span> <span class="key">sealed</span> record <span class="custkey">GetEmployeeByIdQuery</span>(<span class="key">int</span> Id) : <span class="custkey">IRequest</span>&lt;EmployeeDTO&gt
{
} </code></pre>
</div>



<br>
<div style="padding-left: 0.9375rem;">
<div style="padding-bottom: 0.3125rem;"><b><i>Query Handler:</i></b></div>
<pre class="pchl" style="margin-top:0;"><code><span class="key">public</span> <span class="key">sealed</span> record <span class="custkey">GetEmployeeByIdQueryHandler</span> : <span class="custkey">IRequestHandler</span>&lt;GetEmployeeByIdQuery, EmployeeDTO&gt
{
    <span class="key">public</span> <span class="custkey">GetEmployeeByIdQueryHandler</span>(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    <span class="key">private</span> <span class="key">readonly</span> ApplicationDbContext _dbContext;

    <span class="key">public</span> <span class="key">async</span> Task&lt;EmployeeDTO&gt Handle(GetEmployeeByIdQuery request, CancellationToken cancellationToken)
    {
        <span class="key">var</span> result = <span class="key">await</span> _dbContext.Employees
            .AsNoTracking()
            .FirstOrDefaultAsync(w =&gt w.Id == request.Id, cancellationToken);

        <span class="key">return</span> <span class="key">new</span> EmployeeDTO
        {
            Id = result.Id,
            Name = result.Name,
            EmailId = result.EmailId,
            Gender = result.Gender,
            RoleId = result.RoleId
        };
    }
} </code></pre>
</div>



<br><br>



<h3 class="wp-block-heading" id="create-commands"><strong>Create Commands</strong></h3>



<br>



<h4 class="wp-block-heading" id="a-create-employee"><strong>a. Create Employee:</strong></h4>



<br>
<div style="padding-left: 0.9375rem;">
<div style="padding-bottom: 0.3125rem;"><b><i>Command:</i></b></div>
<pre class="pchl" style="margin-top:0;"><code><span class="key">public</span> <span class="key">sealed</span> record <span class="custkey">CreateEmployeeCommand</span>(EmployeeDTO EmployeeDTO) : <span class="custkey">IRequest</span>&lt;EmployeeDTO&gt
{
} </code></pre>
</div>



<br>
<div style="padding-left: 0.9375rem;">
<div style="padding-bottom: 0.3125rem;"><b><i>Command Handler:</i></b></div>
<pre class="pchl" style="margin-top:0;"><code><span class="key">public</span> <span class="key">sealed</span> record <span class="custkey">CreateEmployeeCommandHandler</span> : <span class="custkey">IRequestHandler</span>&lt;CreateEmployeeCommand, EmployeeDTO&gt
{
    <span class="key">public</span> <span class="custkey">CreateEmployeeCommandHandler</span>(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    <span class="key">private</span> <span class="key">readonly</span> ApplicationDbContext _dbContext;

    <span class="key">public</span> <span class="key">async</span> Task&lt;EmployeeDTO&gt Handle(CreateEmployeeCommand request, CancellationToken cancellationToken)
    {
        <span class="key">var</span> employee = <span class="key">new</span> EmployeeModel
        {
            Name = request.EmployeeDTO.Name,
            Gender = request.EmployeeDTO.Gender,
            EmailId = request.EmployeeDTO.EmailId,
            RoleId = request.EmployeeDTO.RoleId,
        };

        _dbContext.Employees.Add(employee);
        <span class="key">await</span> _dbContext.SaveChangesAsync(cancellationToken);
        <span class="key">return</span> request.EmployeeDTO;
    }
} </code></pre>
</div>
<br><br>



<h4 class="wp-block-heading" id="b-update-employee"><strong>b. Update <strong>Employee</strong>:</strong></h4>



<br>
<div style="padding-left: 0.9375rem;">
<div style="padding-bottom: 0.3125rem;"><b><i>Command:</i></b></div>
<pre class="pchl" style="margin-top:0;"><code><span class="key">public</span> <span class="key">sealed</span> record <span class="custkey">UpdateEmployeeCommand</span>(EmployeeDTO EmployeeDTO) : <span class="custkey">IRequest</span>&lt;EmployeeDTO&gt
{
} </code></pre>
</div>



<br>
<div style="padding-left: 0.9375rem;">
<div style="padding-bottom: 0.3125rem;"><b><i>Command Handler:</i></b></div>
<pre class="pchl" style="margin-top:0;"><code><span class="key">public</span> <span class="key">sealed</span> record <span class="custkey">UpdateEmployeeCommandHandler</span> : <span class="custkey">IRequestHandler</span>&lt;UpdateEmployeeCommand, EmployeeDTO&gt
{
    <span class="key">public</span> <span class="custkey">UpdateEmployeeCommandHandler</span>(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    <span class="key">private</span> <span class="key">readonly</span> ApplicationDbContext _dbContext;

    <span class="key">public</span> <span class="key">async</span> Task&lt;EmployeeDTO&gt Handle(UpdateEmployeeCommand request, CancellationToken cancellationToken)
    {
        <span class="key">var</span> employee = <span class="key">new</span> EmployeeModel
        {
            Id = request.EmployeeDTO.Id,
            Name = request.EmployeeDTO.Name,
            Gender = request.EmployeeDTO.Gender,
            EmailId = request.EmployeeDTO.EmailId,
            RoleId = request.EmployeeDTO.RoleId,
        };

        _dbContext.Employees.Update(employee);
        <span class="key">await</span> _dbContext.SaveChangesAsync(cancellationToken);
        <span class="key">return</span> request.EmployeeDTO;
    }
} </code></pre>
</div>
<br><br>



<h4 class="wp-block-heading" id="c-delete-employee"><strong>c. Delete <strong>Employee</strong>:</strong></h4>



<br>
<div style="padding-left: 0.9375rem;">
<div style="padding-bottom: 0.3125rem;"><b><i>Command:</i></b></div>
<pre class="pchl" style="margin-top:0;"><code><span class="key">public</span> <span class="key">sealed</span> record <span class="custkey">DeleteEmployeeCommand</span>(<span class="key">int</span> id) : <span class="custkey">IRequest</span>
{
} </code></pre>
</div>



<br>
<div style="padding-left: 0.9375rem;">
<div style="padding-bottom: 0.3125rem;"><b><i>Command Handler:</i></b></div>
<pre class="pchl" style="margin-top:0;"><code><span class="key">public</span> <span class="key">class</span> <span class="custkey">DeleteEmployeeCommandHandler</span> : <span class="custkey">IRequestHandler</span>&lt;DeleteEmployeeCommand&gt
{
    <span class="key">public</span> <span class="custkey">DeleteEmployeeCommandHandler</span>(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    <span class="key">private</span> <span class="key">readonly</span> ApplicationDbContext _dbContext;

    <span class="key">public</span> <span class="key">async</span> Task Handle(DeleteEmployeeCommand request, CancellationToken cancellationToken)
    {
        <span class="key">var</span> employee = <span class="key">await</span> _dbContext.Employees.
            Where(w=&gt w.Id == request.id).
            FirstOrDefaultAsync(cancellationToken);

        <span class="key">if</span> (employee != <span class="key">null</span>)
        {
            _dbContext.Employees.Remove(employee);
            <span class="key">await</span> _dbContext.SaveChangesAsync(cancellationToken);
        }
    }
} </code></pre>
</div>



<br><br><br>



<p><strong>10) Create API endpoints:</strong> Now we have all the required commands/queries and handlers in place, let’s wire them up with APIs. For this demonstration, we will use a controller named &#8220;EmployeeController&#8221; to implement CRUD operations, each of which will execute the corresponding query or command handler via MediatR. You can use other mechanisms like Minimal API to configure endpoints.</p>



<pre class="pchl" style="white-space:pre; !important"><code><span class="key">public</span> <span class="key">class</span> <span class="custkey">EmployeeController</span> : Controller
{
    <span class="key">private</span> <span class="custkey">IMediator</span> _mediator;
    <span class="key">protected</span> <span style="background:#f2f19d;"><span class="custkey">IMediator</span> Mediator</span> =&gt _mediator ??= HttpContext.RequestServices.GetService&lt;<span class="custkey">IMediator</span>&gt();


    [<span class="custkey">HttpGet</span>(<span class="str" style="background:#f2f19d;">"GetAll"</span>)]
    <span class="key">public</span> <span class="key">async</span> Task&lt;IActionResult&gt GetAllEmployee(CancellationToken cancellationToken)
    {
        <span class="key">var</span> query = <span class="key">new</span> GetAllEmployeeQuery();
        <span class="key">return</span> Ok(<span class="key">await</span> Mediator.Send(query, cancellationToken));
    }

    [<span class="custkey">HttpGet</span>(<span class="str" style="background:#f2f19d;">"GetById/{id}"</span>)]
    <span class="key">public</span> <span class="key">async</span> Task&lt;IActionResult&gt GetEmployeeById(<span class="key">int</span> id, CancellationToken cancellationToken)
    {
        <span class="key">var</span> query = <span class="key">new</span> GetEmployeeByIdQuery(id);
        <span class="key">return</span> Ok(<span class="key">await</span> Mediator.Send(query, cancellationToken));
    }

    [<span class="custkey">HttpPost</span>(<span class="str" style="background:#f2f19d;">"Create"</span>)]
    <span class="key">public</span> <span class="key">async</span> Task&lt;IActionResult&gt CreateEmployee([FromBody] EmployeeDTO request, CancellationToken cancellationToken)
    {
        <span class="key">if</span> (!ModelState.IsValid) { 
            <span class="key">return</span> BadRequest(string.Join(Environment.NewLine, ModelState.Values
                                        .SelectMany(x =&gt x.Errors)
                                        .Select(x =&gt x.ErrorMessage))); }

        <span class="key">var</span> command = <span class="key">new</span> UpdateEmployeeCommand(request);
        <span class="key">return</span> Ok(<span class="key">await</span> Mediator.Send(command, cancellationToken));
    }

    [<span class="custkey">HttpPut</span>(<span class="str" style="background:#f2f19d;">"Update"</span>)]
    <span class="key">public</span> <span class="key">async</span> Task&lt;IActionResult&gt UpdateEmployee([FromBody] EmployeeDTO request, CancellationToken cancellationToken)
    {
        <span class="key">if</span> (!ModelState.IsValid)
        {
            <span class="key">return</span> BadRequest(string.Join(Environment.NewLine, ModelState.Values
                                        .SelectMany(x =&gt x.Errors)
                                        .Select(x =&gt x.ErrorMessage)));
        }

        <span class="key">var</span> command = <span class="key">new</span> UpdateEmployeeCommand(request);
        <span class="key">return</span> Ok(<span class="key">await</span> Mediator.Send(command, cancellationToken));
    }

    [<span class="custkey">HttpDelete</span>(<span class="str" style="background:#f2f19d;">"DeleteById/{id}"</span>)]
    <span class="key">public</span> <span class="key">async</span> Task&lt;IActionResult&gt DeleteEmployee(<span class="key">int</span> id, CancellationToken cancellationToken)
    {
        <span class="key">var</span> command = <span class="key">new</span> DeleteEmployeeCommand(id);
        <span class="key">await</span> Mediator.Send(command, cancellationToken);
        <span class="key">return</span> Ok();
    }
} </code></pre>



<br><br><br>



<p><strong>11) Test the Endpoints via Swagger:</strong> The implementation is complete. Now, let&#8217;s test it using Swagger! Build and run your ASP.NET Core application and open the Swagger UI. The screenshots below display the API test results from Swagger. You can also use other Web API testing tools like Postman, Fiddler, etc.</p>



<p class="p-mb-0"><strong><em>adding a new record &#8211; screenshot</em></strong></p>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/cqrs/cqrs-mediator-post-command-handler-call.jpg" alt=""/></figure>



<br><br>



<p class="p-mb-0"><strong><em>getting a record by id &#8211; screenshot</em></strong></p>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/cqrs/cqrs-mediator-get-by-id-query-handler-call.jpg" alt=""/></figure>



<br>
<div id="PageInAd1"></div>
<script>
fetch('/gads/PageInAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd1:', error);
	});
</script>



<br><br>



<h2 class="wp-block-heading" id="conclusion"><strong>Conclusion</strong></h2>



<p class="custp1">We learned how CQRS and the Mediator pattern work, explored how to implement them using the MediatR library, and also covered Entity Framework Core and the Vertical Slice Architecture approach in a .NET 8 Web API.</p>



<br><br>
<script src="/my-js/latesttop10post.js" type="text/javascript"></script>
<input type="hidden" id="cids" value="191,3,59,71">
<div id="latestPostlist"></div>
<br>



<div class="wp-block-rank-math-toc-block toc-cust" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#what-is-cqrs">What is CQRS?</a></li><li><a href="#why-use-cqrs">Why Use CQRS?</a></li><li><a href="#what-is-mediator">What is Mediator?</a></li><li><a href="#cqrs-and-mediator-implementation">CQRS and Mediator Implementation</a><ul><li><a href="#create-queries">Create Queries</a><ul><li><a href="#a-get-all-employees">a. Get All Employees:</a></li><li><a href="#b-get-employee-by-id">b. Get Employee By Id:</a></li></ul></li><li><a href="#create-commands">Create Commands</a><ul><li><a href="#a-create-employee">a. Create Employee:</a></li><li><a href="#b-update-employee">b. Update Employee:</a></li><li><a href="#c-delete-employee">c. Delete Employee:</a></li></ul></li></ul></li><li><a href="#conclusion">Conclusion</a></li></ul></nav></div>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/implementing-cqrs-mediator-pattern-web-api-aspnet-core/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Domain Driven Design (DDD) approach in .NET Applications</title>
		<link>https://www.codeindotnet.com/domain-driven-design-ddd-approach/</link>
					<comments>https://www.codeindotnet.com/domain-driven-design-ddd-approach/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Tue, 04 Jun 2024 13:05:13 +0000</pubDate>
				<category><![CDATA[Design Pattern Architecture]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=7354</guid>

					<description><![CDATA[In this article, we will learn about the Domain-Driven Design pattern and get a basic idea of how to organize the layers and what components each layer can have, for building robust enterprise applications. What is Domain Driven Design (DDD)? DDD is a software development architecture-style approach that tells you how to manage your domain [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p> </p>



<div id="PageInHoriAd1"></div>
<script>
fetch('/gads/PageInHoriAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInHoriAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInHoriAd1:', error);
	});
</script>



<div class="wp-block-rank-math-toc-block toc-cust" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#what-is-domain-driven-design-ddd">What is Domain Driven Design (DDD)?</a><ul><li><a href="#pros">Pros:</a></li><li><a href="#cons">Cons:</a></li></ul></li><li><a href="#domain-driven-design-folder-structure">Domain Driven Design &#8211; Folder Structure</a></li></ul></nav></div>



<br><br>



<p>In this article, we will learn about the Domain-Driven Design pattern and get a basic idea of how to organize the layers and what components each layer can have, for building robust enterprise applications.</p>



<br>



<h2 class="wp-block-heading hLBRed" id="what-is-domain-driven-design-ddd"><strong>What is Domain Driven Design (DDD)?</strong></h2>



<br>



<p>DDD is a software development architecture-style approach that tells you how to manage your domain complexity.</p>



<p>Eric Evans is the author of <em>&#8220;Domain-Driven Design: Tackling Complexity in the Heart of Software&#8221;</em> which introduced and elaborated on the principles &amp; practices of Domain-Driven Design (DDD), published in 2003.</p>



<p>DDD is only intended for large projects, like more than 6 or 8 months, with large complexity. Domain refers to the subject area around which the application that is being developed is centered. For example, the topic/domain could be &#8220;online order processing&#8221; which you can use to develop an Online Shopping Application. It can have multiple domains like delivery, transport and others within the same application.</p>



<p>The goal of implementing DDD is to handle complex scenarios so that domain experts and developers can collaborate effectively with minimal misunderstanding and arguments.</p>



<br>



<figure class="wp-block-image size-large"><img decoding="async" src="https://www.codeindotnet.com/img/1/ddd/domain-driven-design-ddd-2.jpg" alt="Domain Driven Design Pattern"/></figure>



<div><u>Domain Driven Design &#8211; Diagram</u></div>



<br><br>



<h3 class="wp-block-heading" id="pros"><strong>Pros:</strong></h3>



<ul class="wp-block-list">
<li><strong>Simple communication:</strong> Communication between developers &amp; experts becomes much easier</li>



<li><strong>Object-oriented:</strong> DDD is Object-oriented which gives more flexibility, the entire system can be modified &amp; improved regularly.</li>



<li><strong>Structured Complexity</strong>: By breaking down the domain into smaller, manageable parts (entities, value objects, aggregates, etc.), DDD helps in managing the inherent complexity of large systems.</li>



<li><strong>Bounded Contexts</strong>: DDD encourages defining clear boundaries for different parts of the system, known as bounded contexts, which isolate different domains and reduce dependencies.</li>



<li><strong>Clear Separation of Concerns</strong>: By organizing code around the business domain, DDD ensures that changes in business logic are localized, reducing the risk of unintended side effects.</li>



<li><strong>Test-Driven Development (TDD)</strong>: DDD naturally complements TDD by encouraging the development of small, focused units of code that are easy to test.</li>
</ul>



<br>



<h3 class="wp-block-heading" id="cons"><strong>Cons:</strong></h3>



<ul class="wp-block-list">
<li><strong>Domain knowledge required:</strong> There has to be at least one domain specialist who understands the precise characteristics of the subject that&#8217;s at the center of the application</li>



<li><strong>Doesn&#8217;t work for highly technical projects: </strong>DDD is perfect for applications that have complex business logic, not which is highly technical.</li>
</ul>



<br><br>



<h2 class="wp-block-heading hLBRed" id="domain-driven-design-folder-structure"><strong>Domain Driven Design &#8211; Folder Structure</strong></h2>



<br>



<figure class="wp-block-image size-large"><img decoding="async" src="https://www.codeindotnet.com/img/1/ddd/domain-driven-design-ddd-1.jpg" alt=""/></figure>



<br>



<p>Let&#8217;s look at the diagram above to understand how to create folder structures and see what files can go in each folder.</p>



<p><strong><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color">Note:</mark></strong> These structures/ components can be different for each application depending on business needs, so you can change them as needed. </p>



<br>



<pre class="pchl"><code>
<b style="font-size: 22px;">Domain:</b>

	&#128193; Abstractions 
		&#128193; Repositories
			- IRepository
			- IUnitOfWork.cs

	&#128193; Errors
		- DomainErrors.cs (static error classes)

	&#128193; Enumerations
	
	&#128193; Exceptions
		- BadRequestException.cs
		- NotFoundException.cs

	&#128193; Models/Entities
		- EmployeeEntity.cs

	&#128193; Primitives
		- JsonResult.cs

	- AssemblyReference.cs


<b style="font-size: 22px;">Application:</b>
<span class="com">// ProjectReference = Domain.csproj</span>

	&#128193; Behaviours
		- ValidationBehaviours.cs

	&#128193; Exceptions

	&#128193; Errors
		- ValidationErrors.cs (static error classes)

	&#128193; Features (Vertical Slice Architecture)
		&#128193; Feature1[Employee] (CQRS Design Pattern using MediatR)
			&#128193; Command
				&#128193; Create
					- CreateEmployeeCommand.cs
					- CreateEmployeeCommandHandler.cs
			&#128193; Queries
				&#128193; GetAll
					- GetAllEmployeeQuery.cs
					- GetAllEmployeeQueryHandler.cs

	- AssemblyReference.cs				


<b style="font-size: 22px;">Infrastructure:</b>
<span class="com">// ProjectReference = Domain.csproj</span>

	&#128193; Authentication
		- JwtProvider.cs
		- JwtSettings.cs

	&#128193; Configurations
	
	&#128193; Emails
		- MailSettings.cs
		- EmailService.cs

	&#128193; Logging

	&#128193; Messaging
		- MessageSettings.cs

	&#128193; Notifications
		- EmailNotificationService.cs

	&#128193; Migrations
		- ApplicationDbContextModelSnapshot.cs

	&#128193; Repositories
		- EmployeeRepository.cs
		- GenericRepository.cs

	- ApplicationDbContext.cs

	- AssemblyReference.cs

	
<b style="font-size: 22px;">Presentation:</b>
<span class="com">// ProjectReference = Application.csproj</span>

	&#128193; Controllers
		- EmployeeController.cs

	- AssemblyReference.cs


<b>Web:</b>
<span class="com">// ProjectReference = Infrastructure.csproj</span>
<span class="com">// ProjectReference = Presentation.csproj</span>

	&#128193; Middleware
		&#128193; ExceptionHandling.cs 
</code></pre>



<br>



<ul class="wp-block-list">
<li><strong>The Domain Layer</strong> is the core of the application, containing the business logic and rules. It represents the fundamental business concepts and behaviors, value objects, rules, abstractions, base classes, etc.</li>



<li><strong>The Application Layer</strong> coordinates the application&#8217;s activities, serving as a mediator between the domain layer and the presentation/infrastructure layers. It doesn&#8217;t handle business rules but coordinates tasks using domain objects.</li>



<li><strong>The Infrastructure Layer</strong> provides technical capabilities to support the other layers. It handles concerns such as data persistence, messaging, logging, and external integrations.</li>



<li><strong>The Presentation Layer</strong> is responsible for the user interface and interaction. It handles the display of information and user input, interacting with the application layer to execute commands and retrieve data. For example controllers or User Interfaces (UI) or any front-end interface</li>
</ul>



<p>To support Dependency Injection you need to define all of your service registration inside the Web application. The web applications will have access to the controllers that are defined in the Presentation layer and will have access to anything that is defined inside our application. </p>



<p><a href="Note:"><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color"><strong>Note:</strong></mark></a> Don&#8217;t put the Controller directly in the Web application. If you do, it can access the Infrastructure project, for example allowing direct database access using something like _dbcontext. This breaks the CQRS pattern for separating read/write operations, making it impossible to enforce the proper architecture. Instead, place the Controller in the Presentation Class library, where we can control all the libraries we are referencing.</p>



<div id="PageInAd1"></div>
<script>
fetch('/gads/PageInAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd1:', error);
	});
</script>



<br>
<script src="/my-js/latesttop10post.js" type="text/javascript"></script>
<input type="hidden" id="cids" value="3,59,71">
<div id="latestPostlist"></div>
<br>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/domain-driven-design-ddd-approach/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
