<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Meisam Alifallhi on Medium]]></title>
        <description><![CDATA[Stories by Meisam Alifallhi on Medium]]></description>
        <link>https://medium.com/@araxis?source=rss-60cea8e190f4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Y3a-BjRZT9lUQ9IHrbP9gg.jpeg</url>
            <title>Stories by Meisam Alifallhi on Medium</title>
            <link>https://medium.com/@araxis?source=rss-60cea8e190f4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 14:45:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@araxis/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[C# Source Generators: Getting Started]]></title>
            <link>https://medium.com/@araxis/c-source-generators-getting-started-bcea0d88db5?source=rss-60cea8e190f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcea0d88db5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Meisam Alifallhi]]></dc:creator>
            <pubDate>Sun, 30 Apr 2023 17:20:18 GMT</pubDate>
            <atom:updated>2023-04-30T17:20:18.646Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*2DKVt4ElAQ6GjA31EofZnA.jpeg" /></figure><p>Source Generators are a powerful tool that allow developers to automatically generate code during the compilation process. They can help reduce boilerplate code, improve performance, and enable new coding patterns. In this article, we will walk through creating a custom Source Generator to generate code based on specific conditions for a given set of methods.</p><h3>What is a Source Generator?</h3><blockquote>A Source Generator is a piece of code that runs during compilation and can inspect your program to produce additional files that are compiled together with the rest of your code.</blockquote><h3><strong>How do Source Generators work?</strong></h3><p>During compilation, Source Generators analyze code and metadata and generate additional source code based on those analyses. These are like plugins for the compiler that are executed during compilation.When the compiler loads the Source Generator, it analyzes the code and metadata to identify syntax nodes and semantic information relevant to the Source Generator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u95iQhjo0xWmKnQnSqLX5A.png" /></figure><p>Source Generator analyzes syntax nodes and generates additional source code based on the analysis. This generated code is added to the compilation as if it were written by the developer. Compilation is complete, and the generated code is included in the assembly.</p><h3><strong>When to use Source Generators?</strong></h3><p>Source Generators are ideal for situations where you need to automate repetitive tasks, enforce coding patterns or generate code based on specific conditions in your codebase.Here are some situations where source generators can be particularly useful:</p><ol><li>Reducing boilerplate code: If you find yourself writing the same code over and over again, a source generator can automatically generate that code for you. This can save time and reduce the likelihood of errors caused by manual code duplication.</li><li>Improving performance: Source generators can generate code that is optimized for specific scenarios, such as data serialization or network communication. This can help improve the performance of the application by reducing the amount of overhead required to perform these operations.</li><li>Enabling new coding patterns: Source generators can be used to enable new coding patterns, such as compile-time dependency injection or aspect-oriented programming. This can help developers write more modular, maintainable code that is easier to test and debug.</li><li>Adapting to changing requirements: Source generators can be used to adapt code to changing requirements, such as changes to an external API or changes to business logic. This can help reduce the amount of manual code updates required and improve the overall flexibility of the codebase.</li><li>Generating code for cross-cutting concerns: Source generators can be used to generate code for cross-cutting concerns, such as logging, error handling, or performance monitoring. This can help ensure that these concerns are addressed consistently across the application and reduce the risk of errors caused by manual coding.</li></ol><h3><strong>Understanding the Components of a Source Generator</strong></h3><p>A Source Generator consists of two main components that work together to provide a seamless and efficient code generation process:</p><p>the <strong><em>ISyntaxReceiver</em></strong> and the <strong><em>ISourceGenerator</em></strong>. By understanding the components and their relationship, you can create custom Source Generators tailored to your specific requirements.</p><p>The <strong><em>ISyntaxReceiver</em></strong> is responsible for collecting and filtering syntax nodes during the compilation process based on specific conditions. The <strong><em>ISourceGenerator</em></strong> is responsible for generating code based on the filtered syntax nodes collected by the ISyntaxReceiver.</p><p>These two components work together as follows:</p><ol><li>The <strong><em>ISyntaxReceiver</em></strong> collects and filters syntax nodes during the compilation process.</li><li>The <strong><em>ISourceGenerator</em></strong> receives the filtered syntax nodes from the ISyntaxReceiver.</li><li>The <strong><em>ISourceGenerator</em></strong> generates code based on the filtered syntax nodes.</li></ol><blockquote>You can also filter syntax nodes directly in the ISourceGenerator’s Execute method, but using an ISyntaxReceiver is more efficient because it allows you to filter syntax nodes during the compilation process, avoiding unnecessary overhead.</blockquote><h3><strong>Create a custom Source Generator step-by-step.</strong></h3><ol><li><strong>Setting up a Source Generator Project</strong><br>Create a new Class Library (.NET Standard) project targeting netstandard2.0. To use Source Generators, you need to add the <strong>following NuGet packages to your project:</strong><br>- Microsoft.CodeAnalysis.CSharp<br>- Microsoft.CodeAnalysis.Analyzers</li><li><strong>Implementing a Custom Syntax Receiver</strong></li></ol><pre> public class CustomSyntaxReceiver : ISyntaxReceiver<br> {<br>     public List&lt;MethodDeclarationSyntax&gt; CandidateMethods { get; } = new();<br>     public void OnVisitSyntaxNode(SyntaxNode syntaxNode)<br>     {<br>         if (syntaxNode is MethodDeclarationSyntax methodDeclaration &amp;&amp;<br>             methodDeclaration.AttributeLists.Any(al =&gt; al.Attributes.Any(a =&gt; a.Name.ToString() == &quot;MyCustomAttribute&quot;)))<br>         {<br>             CandidateMethods.Add(methodDeclaration);<br>         }<br>     }<br>}<br></pre><p>3. <strong>Implementing a Custom Source Generator</strong></p><pre> [Generator]<br>public class CustomSourceGenerator : ISourceGenerator<br>{<br>   public void Initialize(GeneratorInitializationContext context)<br>   {<br>       context.RegisterForSyntaxNotifications(() =&gt; new CustomSyntaxReceiver());<br>   }<br>   //Inside the `Execute` method, retrieve the SyntaxReceiver and generate code based on the filtered methods. Here&#39;s a simple example that generates a static class with a method that prints the names of the filtered methods:<br>   public void Execute(GeneratorExecutionContext context)<br>   {<br>       if (context.SyntaxReceiver is not CustomSyntaxReceiver receiver)<br>           return;<br>  <br>       var sourceBuilder = new StringBuilder();<br>       sourceBuilder.AppendLine(&quot;using System;&quot;);<br>       sourceBuilder.AppendLine(&quot;namespace GeneratedCode&quot;);<br>       sourceBuilder.AppendLine(&quot;{&quot;);<br>       sourceBuilder.AppendLine(&quot;    public static class GeneratedMethodsInfo&quot;);<br>       sourceBuilder.AppendLine(&quot;    {&quot;);<br>       sourceBuilder.AppendLine(&quot;        public static void PrintMethodNames()&quot;);<br>       sourceBuilder.AppendLine(&quot;        {&quot;);<br>  <br>       foreach (var method in receiver.CandidateMethods)<br>       {<br>           sourceBuilder.AppendLine($&quot;            Console.WriteLine(\&quot;{method.Identifier}\&quot;);&quot;);<br>       }<br>  <br>       sourceBuilder.AppendLine(&quot;        }&quot;);<br>       sourceBuilder.AppendLine(&quot;    }&quot;);<br>       sourceBuilder.AppendLine(&quot;}&quot;);<br>  <br>       context.AddSource(&quot;GeneratedMethodsInfo&quot;, sourceBuilder.ToString());<br>    }<br>}</pre><p>4. <strong>Add the source generator from a project as an analyzer</strong></p><pre>&lt;!-- replacing paths and names appropriately --&gt;<br>&lt;ItemGroup&gt;<br><br>    &lt;ProjectReference Include=&quot;path-to-sourcegenerator-project.csproj&quot; <br>                      OutputItemType=&quot;Analyzer&quot;<br>                      ReferenceOutputAssembly=&quot;false&quot; /&gt;<br>&lt;/ItemGroup&gt;</pre><p>By implementing a custom ISyntaxReceiver and ISourceGenerator, you can create a powerful and efficient Source Generator that generates code based on specific conditions . Using an ISyntaxReceiver allows you to filter syntax nodes during the compilation process, reducing overhead and improving performance.</p><p>In summary, understanding the components of a Source Generator and their relationship is crucial for creating custom Source Generators tailored to your specific requirements. By leveraging the power of ISyntaxReceivers and ISourceGenerators, you can enhance your development process and take full advantage of the benefits offered by Source Generators in C#.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcea0d88db5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SimpleResult: A Better Alternative to Traditional Exception Handling]]></title>
            <link>https://medium.com/@araxis/simpleresult-a-better-alternative-to-traditional-exception-handling-aff600919a40?source=rss-60cea8e190f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/aff600919a40</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Meisam Alifallhi]]></dc:creator>
            <pubDate>Sun, 16 Apr 2023 12:39:17 GMT</pubDate>
            <atom:updated>2023-04-16T12:42:35.543Z</atom:updated>
            <content:encoded><![CDATA[<p>Developing .NET applications often involves dealing with various operation results and potential errors. Traditional error handling approaches in .NET, such as exceptions and multiple return statements, can lead to code that is difficult to read, maintain, and prone to errors. In this article, I will introduce <a href="https://github.com/araxis/SimpleResult">SimpleResult</a>, a lightweight library that provides a convenient alternative to traditional error handling. I will discuss the challenges of handling exceptions in .NET applications and demonstrate how SimpleResult can improve your codebase with various code samples.</p><h3>The Challenges of Traditional Exception Handling in .NET</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*COSB6MpObv9UZRCLTAdjQg.jpeg" /></figure><p>Traditional error handling in .NET often relies on throwing and catching exceptions. This approach has several drawbacks:</p><ol><li><strong>Performance:</strong> Throwing exceptions can be expensive in terms of performance, particularly when used for expected error scenarios.</li><li><strong>Readability:</strong> Code that heavily relies on exceptions can be difficult to read, as it requires developers to follow complex control flow structures.</li><li><strong>Maintainability:</strong> When using multiple return statements and exceptions, it can be challenging to understand the possible outcomes of a method. This complexity can lead to bugs and make it harder to modify the code in the future.</li><li><strong>Error Propagation:</strong> When exceptions are used as the primary means of error handling, they must be propagated up the call stack, which can be cumbersome and error-prone.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*oUj-XNzpv0PlDlYmQ9lZag.jpeg" /></figure><p><a href="https://github.com/araxis/SimpleResult">SimpleResult </a>offers a convenient alternative to traditional error handling, allowing you to handle success and failure scenarios in a consistent and straightforward manner. By adopting this library, you can write cleaner code that is easier to understand and less prone to errors.</p><h3>Introducing SimpleResult</h3><p><a href="https://github.com/araxis/SimpleResult">SimpleResult</a> is a lightweight library that simplifies the handling of operation results in .NET applications. It provides a convenient way to manage success and failure scenarios, making your code more readable and maintainable. The library helps developers avoid the pitfalls of traditional exception handling and reduces the likelihood of errors in their code.</p><h3>Installing SimpleResult</h3><p>To get started with SimpleResult, install the library from <a href="https://www.nuget.org/packages/Arax.SimpleResult">NuGet</a></p><pre>Install-Package Arax.SimpleResult</pre><h3>Using SimpleResult in Your .NET Applications</h3><p>The following sections will guide you through various ways to utilize SimpleResult in your .NET applications. Each section will include code samples demonstrating how to use the library effectively.</p><h3>Creating Results</h3><p>SimpleResult provides a set of static methods and implicit conversion operators to create instances of Result and Result&lt;T&gt;:</p><pre>var successResult = Result.Success();<br>var intResult = Result&lt;int&gt;.Success(12);<br>Result&lt;int&gt; intResult = 12;<br>var failureResult = Result.Fail(&quot;An error occurred&quot;);<br>var failureResultWithValue = Result&lt;int&gt;.Fail(&quot;An error occurred&quot;);<br>var failureResultErors = Result.Fail(&quot;An error occurred&quot;, &quot;Another error occurred&quot;);<br>var failureResultException = Result.Fail(new InvalidOperationException());<br>var failureResultException = Result.Fail(new InvalidOperationException(), &quot;An error occurred&quot;);<br>Result failure = new InvalidOperationException();</pre><h3>Basic Usage</h3><p>You can use the properties and methods provided by the Result and Result&lt;T&gt; classes to access the result status, value, exception, or errors:</p><pre>public void UseResult()<br>{<br>    var result = GetPerson(1);<br>    var isSuccess = result.IsSuccess;<br>    var isFailure = result.IsFailure;<br>    <br>    var person = result.GetOrDefault();<br>    var personWithCustomDefault = result.GetOrDefault(new Person(&quot;custom&quot;));<br>    <br>    var exception = result.ExceptionOrNull();<br>    var errors = result.Errors;<br>}</pre><h3>Performing Actions on Success</h3><p>The OnSuccess method provided by SimpleResult allows you to execute actions when the result is successful, without having to check the status of the result manually. This leads to cleaner and more readable code, as well as a reduced chance of forgetting to handle success scenarios.</p><pre>public Result SendEmail(string recipient, string subject, string body)<br>{<br>    // Your email sending logic here<br>}<br><br>// ...<br><br>var sendEmailResult = SendEmail(&quot;example@example.com&quot;, &quot;Subject&quot;, &quot;Email body&quot;);<br><br>sendEmailResult.OnSuccess(() =&gt; {<br>        Console.WriteLine(&quot;Email sent successfully.&quot;);<br>    });<br><br>//or asyn operation<br> await result.OnSuccess(async _=&gt;<br> {<br>      await DoSomethingAsync(_);<br>  });<br></pre><h3>Handling Failures and Exceptions</h3><p>SimpleResult makes it easy to handle failures and exceptions in a consistent and expressive manner. Here’s a more detailed look at how to use SimpleResult for handling various failure scenarios:</p><p><strong>Handling failures</strong>: Use the OnFailure method to perform an action when the result is unsuccessful. The OnFailure method accepts a delegate that takes the exception (which can be null) and an array of error messages as parameters:</p><pre>var result = DangerousOperation();<br>result.OnFailure((exception, errs) =&gt; Console.WriteLine($&quot;Exception: {exception?.Message ?? &quot;None&quot;}, errors: {string.Join(&quot;, &quot;, errs)}&quot;));<br><br>//asyn operation<br> await result.OnFailure&lt;CustomError&gt;(async (exception, errors) =&gt;<br> {<br>      Console.WriteLine($&quot;Exception: {exception?.Message ?? &quot;None&quot;}, errors: {string.Join(&quot;, &quot;, errors)}&quot;);<br>      await HandleCustomErrorAsync(errors);<br> });</pre><p><strong>Handling exceptions</strong>: Use the OnException method to perform an action when the result has failed due to an exception. The OnException method accepts a delegate that takes the exception and an array of error messages as parameters:</p><pre>result.OnException((ex, errs) =&gt; Console.WriteLine($&quot;Exception: {ex.Message}, errors: {string.Join(&quot;, &quot;, errs)}&quot;));<br><br>//asyn operation<br> await result.OnException(async (ex, errors) =&gt;<br> {<br>      Console.WriteLine($&quot;Exception: {ex.Message}, errors: {string.Join(&quot;, &quot;, errors)}&quot;);<br>      await HandleCustomErrorAsync(errors);<br> });</pre><p><strong>Handling specific exceptions:</strong> If you want to handle a specific type of exception, you can use the generic OnException&lt;T&gt; method, where T is the type of exception:</p><pre>result.OnException&lt;DivideByZeroException&gt;((ex, errors) =&gt; Console.WriteLine($&quot;Caught DivideByZeroException: {ex.Message}&quot;));<br><br>//asyn operation<br> await result.OnException&lt;DivideByZeroException&gt;(async (ex, errors) =&gt;<br> {<br>      Console.WriteLine($&quot;Caught DivideByZeroException: {ex.Message}&quot;);<br>      await HandleCustomErrorAsync(errors);<br> });</pre><p><strong>Handling inner exceptions:</strong> To handle exceptions that are wrapped as inner exceptions, use the OnInnerException&lt;T&gt; method, where T is the type of inner exception:</p><pre>result.OnInnerException&lt;InvalidOperationException&gt;((ex, errors) =&gt; Console.WriteLine($&quot;Caught InvalidOperationException as InnerException: {ex.Message}&quot;));<br><br>//asyn operation<br> await result.OnInnerException&lt;InvalidOperationException&gt;(async (ex, errors) =&gt;<br> {<br>      Console.WriteLine($&quot;Caught InvalidOperationException as InnerException: {ex.Message}&quot;);<br>      await HandleCustomErrorAsync(errors);<br> });</pre><p>By using these methods, you can handle failures and exceptions in a more expressive and consistent way compared to traditional exception handling approaches. Moreover, SimpleResult allows you to separate success and failure handling, making your code more readable and maintainable.</p><h3>Switching Between Success and Failure Actions</h3><p>The Switch method is another way to execute different actions based on the success or failure of a result. It takes two parameters: onSuccess and onFailure, which are actions that get executed based on the status of the result.</p><p>With the Switch method, you can replace traditional if-else statements for handling the result of an operation with more concise and readable code. Instead of repeating the same checks over and over, you can execute different actions based on the success or failure of the result.</p><p>For example, consider the following code that returns a Result&lt;int&gt;:</p><pre>var result = DoSomething();<br><br>if (result.IsSuccess)<br>{<br>    Console.WriteLine($&quot;Operation succeeded with value: {result.GetOrDefault()}&quot;);<br>}<br>else<br>{<br>    Console.WriteLine($&quot;Operation failed with errors: {string.Join(&quot;, &quot;, result.Errors)}&quot;);<br>}</pre><p>You can use the Switch method to refactor the above code as follows:</p><pre>DoSomething().Switch(<br>    onSuccess: value =&gt; Console.WriteLine($&quot;Operation succeeded with value: {value}&quot;),<br>    onFailure: (exception, errors) =&gt; Console.WriteLine($&quot;Operation failed with errors: {string.Join(&quot;, &quot;, errors)}&quot;)<br>);</pre><blockquote>There are also async versions of the Switch method, allowing you to handle asynchronous actions based on the result of an operation.</blockquote><h3>Transforming Results with Fold</h3><p>The Fold method allows you to transform a Result into another type based on whether the operation succeeded or failed. It accepts two functions: one for handling successful results and another for handling failures. The result of the Fold method is the return value of either the onSuccess function or the onFailure function, depending on the status of the result.</p><pre>var result = DoSomething();<br><br>string message = result.Fold(<br>    onSuccess: () =&gt; &quot;Success&quot;,<br>    onFailure: (exception, errors) =&gt; $&quot;Failure: {string.Join(&quot;, &quot;, errors)}&quot;<br>);<br><br>Console.WriteLine(message);</pre><p>Another Sample</p><pre>var result = GetPerson(1);<br><br>var person = result.Fold(<br>    onSuccess: p =&gt; p,<br>    onFailure: (exception, errors) =&gt; new Person(&quot;Default Person&quot;)<br>);<br><br>Console.WriteLine(person.Name);</pre><blockquote>There are also async versions of the Fold method, allowing you to handle asynchronous actions based on the result of an operation.</blockquote><h3>Mapping a Result to Another Type</h3><p>The Map method is a useful tool for handling program flow when working with results. It allows you to transform a Result&lt;T&gt; to a Result&lt;U&gt; based on a provided transformation function. This can be helpful when you need to take the result of one operation and transform it into a different type for use in another operation.</p><p>In addition to the synchronous Map method, there is also an asynchronous version that allows you to perform the transformation asynchronously. This can be useful when the transformation function itself involves some form of asynchronous operation.</p><p>Using Map in this way can help to make your code more modular and easier to reason about. By breaking down complex operations into smaller, discrete steps, you can make your code more maintainable and easier to test.</p><pre>Result&lt;int&gt; result = Result.Success(42);<br><br>Result&lt;string&gt; stringResult = result.Map(i =&gt; i.ToString());<br>// or async<br>// var stringResult = await result.Map(async i =&gt; await GetSomeStringAsync(i));<br><br>if (stringResult.IsSuccess)<br>{<br>    Console.WriteLine($&quot;The result is {stringResult.Value}&quot;);<br>}<br>else<br>{<br>    Console.WriteLine(&quot;An error occurred&quot;);<br>}</pre><h3>The Benefits of SimpleResult Over Traditional Exception Handling</h3><p>By using SimpleResult in your .NET applications, you can address the issues that traditional exception handling approaches often create:</p><ol><li><strong>Improved code readability:</strong> With SimpleResult, your code becomes easier to read and understand since it reduces the need for multiple try-catch blocks and return statements. This makes it simpler to follow the program flow.</li><li><strong>Better performance:</strong> Exceptions are expensive to create and handle. SimpleResult helps you avoid exceptions in the normal control flow of your application, resulting in better overall performance.</li><li><strong>Less error-prone code:</strong> Managing return values and exceptions together can lead to a cumbersome and error-prone codebase. SimpleResult provides a consistent and straightforward way to handle success and failure scenarios, making your code more maintainable and less prone to errors</li></ol><h3>Conclusion</h3><p>Handling errors and exceptions in .NET applications can be challenging and cumbersome. In traditional approaches, you would need to handle exceptions manually, which could lead to code that is difficult to read and maintain. With SimpleResult, you can handle errors and exceptions more elegantly and intuitively, leading to more manageable code.</p><p>The library offers various methods such as OnSuccess, OnFailure, Switch, Map, and Fold, which allow you to handle successful and unsuccessful scenarios, perform actions based on the result, transform the result, and fold the result into another type.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aff600919a40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OneOf: The Missing Piece in Your C# Development Toolbox]]></title>
            <link>https://medium.com/@araxis/oneof-the-missing-piece-in-your-c-development-toolbox-3774cc8dcd44?source=rss-60cea8e190f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3774cc8dcd44</guid>
            <dc:creator><![CDATA[Meisam Alifallhi]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 09:06:45 GMT</pubDate>
            <atom:updated>2023-04-02T09:06:45.253Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*S5P1TeaXYxMsQ3zzl-FfHg.jpeg" /></figure><p>When writing C# code, we often encounter scenarios where we need to represent a set of related values with different types. This is where discriminated unions come in. They are a data structure that allows us to represent a value that can be one of several possible types. Discriminated unions have many benefits, such as reducing code complexity, improving type safety, and making code more expressive. However, implementing them in C# can be challenging, especially when dealing with nested or complex types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*vRwFGYB3sp4zCHf4rIxWxA.gif" /></figure><p>This is where <a href="https://github.com/mcintyre321/OneOf">OneOf</a>, a simple and powerful C# tool for discriminated unions, comes in. <a href="https://github.com/mcintyre321/OneOf">OneOf</a> is a lightweight library that provides an elegant and type-safe way to represent multiple possible types. It allows us to define an object that can be one of several possible types, without the need for boilerplate code.</p><p><a href="https://github.com/mcintyre321/OneOf">OneOf</a> provides a simple and easy-to-use API that allows us to create unions of up to eight different types. It supports any type that can be used as a C# return type, including classes, interfaces, and primitive types. <a href="https://github.com/mcintyre321/OneOf">OneOf</a> also provides a fluent API that allows us to specify the type and value of the union, making it easy to use in complex scenarios.</p><p><a href="https://github.com/mcintyre321/OneOf">OneOf</a> can be particularly useful in situations where we need to represent the success or failure of an operation. For example, we can use OneOf to define a result type that can be either a success value or an error message.</p><p>To use <a href="https://github.com/mcintyre321/OneOf">OneOf</a> in your project, you can install the NuGet package using the NuGet package manager or the Package Manager Console in Visual Studio. Simply run the following command:</p><pre>Install-Package OneOf</pre><p>Here’s an example:</p><pre>public OneOf&lt;MyResult, string&gt; DoSomething()<br>{<br>    if (success)<br>    {<br>        return new MyResult(...);<br>    }<br>    else<br>    {<br>        return &quot;An error occurred&quot;;<br>    }<br>}</pre><p>In this example, the DoSomething method returns a OneOf&lt;MyResult, string&gt; type, which means it can either return a MyResult object or a string error message. This makes it clear to the caller what the possible outcomes of the method are, and ensures that the caller handles both cases.</p><p>Using <a href="https://github.com/mcintyre321/OneOf">OneOf</a> can also make code more expressive and easier to read. Instead of using nested if statements or switch statements to handle multiple possible outcomes, we can use pattern matching to handle each case separately. For example:</p><pre>var result = DoSomething();<br>switch (result)<br>{<br>    case MyResult myResult:<br>        // Handle success case<br>        break;<br>    case string errorMessage:<br>        // Handle error case<br>        break;<br>}</pre><p><a href="https://github.com/mcintyre321/OneOf">OneOf</a> is an open-source project that is actively maintained and supported by the community. It can be easily installed using NuGet, and its source code is available on GitHub. Overall, OneOf is a simple and powerful tool that makes working with discriminated unions in C# much easier and more expressive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3774cc8dcd44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hexagonal vs. Clean architecture]]></title>
            <link>https://medium.com/@araxis/hexagonal-vs-clean-architecture-b11a6833136e?source=rss-60cea8e190f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b11a6833136e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Meisam Alifallhi]]></dc:creator>
            <pubDate>Sun, 26 Feb 2023 10:54:09 GMT</pubDate>
            <atom:updated>2023-02-26T10:54:09.153Z</atom:updated>
            <content:encoded><![CDATA[<p>Clean Architecture and Hexagonal Architecture are two popular software architecture patterns used in software development. They have similar goals of creating maintainable, testable, and extensible software systems, but differ in their approach to structuring the project and how they achieve these goals. In this article, we’ll explore Clean Architecture and Hexagonal Architecture, compare their differences, pros and cons, and demonstrate how to implement them using C#.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*YSyWUsxhOfTjvsAXQ9bNIQ.gif" /></figure><h3><strong>Clean Architecture</strong></h3><p>Clean Architecture is an architecture pattern that is based on four layers: <strong><em>presentation</em></strong>, <strong><em>application</em></strong>, <strong><em>domain</em></strong>, and <strong><em>infrastructure</em></strong>. The presentation layer is responsible for handling user interactions, the application layer is responsible for handling the business logic, the domain layer is responsible for defining the business entities and their relationships, and the infrastructure layer is responsible for handling external concerns such as databases and web services.</p><figure><img alt="Clean Architecture" src="https://cdn-images-1.medium.com/max/500/1*i1mXlM5LibxErHhvvoo6Ng.png" /></figure><p>The key principles of Clean Architecture include the independence of the layers, the data flow from the outer layers to the inner layers, and the ability to swap out dependencies without affecting the rest of the system. Clean Architecture emphasizes the separation of concerns to make the codebase easier to maintain, test, and extend.</p><p><strong>Project Structure:</strong></p><p>The project structure of Clean Architecture follows a structured layout that enables code reusability and testability. In the project structure, you would typically have a project for the presentation layer, a project for the application layer, a project for the domain layer, a project for the infrastructure layer, and a project for the tests. Each layer would have its own set of interfaces and implementations, with the application layer acting as the bridge between the other layers. Here is an example of the project structure of Clean Architecture:</p><pre>MyProject<br>├── MyProject.Application<br>│   ├── MyProject.Application.csproj<br>│   ├── Services<br>│   ├── UseCases<br>│   └── ViewModels<br>├── MyProject.Domain<br>│   ├── MyProject.Domain.csproj<br>│   ├── Entities<br>│   ├── Interfaces<br>│   └── Services<br>├── MyProject.Infrastructure<br>│   ├── MyProject.Infrastructure.csproj<br>│   ├── Data<br>│   ├── Repositories<br>│   └── Services<br>├── MyProject.Presentation<br>│   ├── MyProject.Presentation.csproj<br>│   ├── Controllers<br>│   ├── Models<br>│   └── Views<br>├── MyProject.Tests<br>│   ├── MyProject.Tests.csproj<br>│   ├── ApplicationTests<br>│   ├── DomainTests<br>│   └── InfrastructureTests<br>└── MyProject.sln</pre><p>The project is divided into five separate projects: MyProject.Application, MyProject.Domain, MyProject.Infrastructure, MyProject.Presentation, and MyProject.Tests.</p><p>The MyProject.Domain project contains the core business logic and defines the entities and interfaces. This layer is at the center of the architecture, and all other layers depend on it.</p><p>The MyProject.Application project contains the application logic, including the use cases and services that operate on the domain entities. This layer is responsible for implementing the business rules and application workflows.</p><p>The MyProject.Infrastructure project contains the implementation details, such as the database access and external services. This layer is responsible for providing the technical details needed to support the application.</p><p>The MyProject.Presentation project contains the user interface and the presentation logic, such as the web application, the desktop application, or the mobile application.</p><p>Finally, the MyProject.Tests project contains the tests for the application. This layer is responsible for ensuring that the application functions correctly and that the behavior of the application is consistent with the business requirements.</p><p><strong>Implementation:</strong></p><p>To implement Clean Architecture in C#, we can use ASP.NET Core. Here is an example of a simple web application that displays a list of books.</p><pre>// Book.cs<br>namespace MyProject.Domain.Entities<br>{<br>    public class Book<br>    {<br>        public int Id { get; set; }<br>        public string Title { get; set; }<br>        public string Author { get; set; }<br>        public int Year { get; set; }<br>    }<br>}<br><br>// IBookRepository.cs<br>using System.Collections.Generic;<br><br>namespace MyProject.Domain.Interfaces<br>{<br>    public interface IBookRepository<br>    {<br>        List&lt;Book&gt; GetAll();<br>    }<br>}<br><br>// BookRepository.cs<br>using MyProject.Domain.Entities;<br>using MyProject.Domain.Interfaces;<br>using System.Collections.Generic;<br><br>namespace MyProject.Infrastructure.Repositories<br>{<br>    public class BookRepository : IBookRepository<br>    {<br>        public List&lt;Book&gt; GetAll()<br>        {<br>            // retrieve list of books from database<br>            return new List&lt;Book&gt;()<br>            {<br>                new Book() { Id = 1, Title = &quot;Clean Code&quot;, Author = &quot;Robert C. Martin&quot;, Year = 2008 },<br>                new Book() { Id = 2, Title = &quot;The Pragmatic Programmer&quot;, Author = &quot;Andrew Hunt and David Thomas&quot;, Year = 1999 },<br>                new Book() { Id = 3, Title = &quot;Design Patterns&quot;, Author = &quot;Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides&quot;, Year = 1994 }<br>            };<br>        }<br>    }<br>}<br><br>// BookService.cs<br>using MyProject.Domain.Entities;<br>using MyProject.Domain.Interfaces;<br>using System.Collections.Generic;<br><br>namespace MyProject.Application.Services<br>{<br>    public class BookService<br>    {<br>        private readonly IBookRepository _bookRepository;<br><br>        public BookService(IBookRepository bookRepository)<br>        {<br>            _bookRepository = bookRepository;<br>        }<br><br>        public List&lt;Book&gt; GetAllBooks()<br>        {<br>            return _bookRepository.GetAll();<br>        }<br>    }<br>}<br><br>// BooksController.cs<br>using Microsoft.AspNetCore.Mvc;<br>using MyProject.Application.Services;<br><br>namespace MyProject.Presentation.Controllers<br>{<br>    [Route(&quot;api/[controller]&quot;)]<br>    [ApiController]<br>    public class BooksController : ControllerBase<br>    {<br>        private readonly BookService _bookService;<br><br>        public BooksController(BookService bookService)<br>        {<br>            _bookService = bookService;<br>        }<br><br>        [HttpGet]<br>        public IActionResult GetBooks()<br>        {<br>            var books = _bookService.GetAllBooks();<br>            return Ok(books);<br>        }<br>    }<br>}</pre><p><strong><em>Pros of Clean Architecture:</em></strong></p><ol><li><strong>Separation of concerns</strong>: Clean Architecture enforces a clear separation of concerns between different parts of the system, which makes the codebase more modular and easier to maintain.</li><li><strong>Testability:</strong> Clean Architecture makes it easier to test the codebase since each layer is independent of the others, and the dependencies are inverted.</li><li><strong>Flexibility:</strong> Clean Architecture makes it easier to swap out dependencies and makes the codebase more flexible and extensible.</li></ol><p><strong><em>Cons of Clean Architecture:</em></strong></p><ol><li><strong>Complexity:</strong> Clean Architecture can be complex, especially for smaller projects, which may not require such a high level of abstraction.</li><li><strong>Learning curve:</strong> Clean Architecture requires developers to have a good understanding of the architecture and the design patterns used, which can increase the learning curve.</li><li><strong>Over-engineering: </strong>Clean Architecture can lead to over-engineering, where developers spend too much time on designing the architecture and not enough on delivering functionality.</li></ol><h3><strong>Hexagonal Architecture</strong></h3><p>Hexagonal Architecture is a software design pattern that emphasizes the separation of concerns by isolating the application’s core logic from the infrastructure components. It does this by dividing the system into two main parts, the <strong>domain </strong>and the <strong>infrastructure</strong>. The domain contains the core business logic of the application, while the infrastructure includes the implementation details of the system.</p><figure><img alt="Hexagonal Architecture" src="https://cdn-images-1.medium.com/max/1024/1*wF_9grzxoLnSENdscTrncQ.png" /></figure><p>The domain layer is where the core business logic of the application is defined. It contains entities, which are objects that represent business concepts or ideas, as well as services, which are responsible for performing operations on these entities. The domain layer is isolated from the infrastructure layer, which means that it does not depend on any specific technology or framework.</p><p>The infrastructure layer, on the other hand, is responsible for providing the technical details that enable the application to run, such as databases, user interfaces, web services, and other external dependencies. The infrastructure layer contains adapters that communicate with external systems, such as a database, a message queue, or a web service, and translates their requests into a format that the domain layer can understand.</p><p>In Hexagonal Architecture, the use of ports and adapters is a key concept that enables the separation of concerns between the domain and infrastructure layers. A port is a contract or an interface that defines a specific functionality or operation that the application provides. An adapter, also known as a driver, implements the port and handles the communication with the external system.</p><p>The ports and adapters pattern allows the application to be flexible and easily maintainable. Since the domain layer is isolated from the infrastructure layer, changes to the infrastructure layer can be made without affecting the domain layer. This makes it easy to swap out adapters or to add new adapters for different external systems.</p><p><strong>Project Structure:</strong></p><p>The project structure of Hexagonal Architecture is divided into four separate projects: domain, application, adapters, and tests. Each of these layers would contain their own set of interfaces and implementations, with the application layer acting as the bridge between the domain and adapter layers.</p><pre>MyProject<br>├── MyProject.Domain<br>│   ├── MyProject.Domain.csproj<br>│   ├── Entities<br>│   ├── Interfaces<br>│   └── Services<br>├── MyProject.Application<br>│   ├── MyProject.Application.csproj<br>│   ├── Services<br>│   └── Interfaces<br>├── MyProject.Adapters<br>│   ├── MyProject.Adapters.csproj<br>│   ├── RestApi<br>│   ├── Database<br>│   └── Interfaces<br>└── MyProject.Tests<br>    ├── MyProject.Tests.csproj<br>    ├── ApplicationTests<br>    └── DomainTests</pre><p>The MyProject.Domain project contains the domain logic, which includes the entities, interfaces, and services.</p><p>The MyProject.Application project contains the application logic, which includes the services and interfaces.</p><p>The MyProject.Adapters project contains the adapters, which include the rest api, database, and interfaces.</p><p>The MyProject.Tests project contains the tests for the application and domain layers.</p><p><strong>Implementation:</strong></p><pre>// Book.cs<br>namespace MyProject.Domain.Entities<br>{<br>    public class Book<br>    {<br>        public int Id { get; set; }<br>        public string Title { get; set; }<br>        public string Author { get; set; }<br>        public int Year { get; set; }<br>    }<br>}<br><br>// IBookRepository.cs<br>using System.Collections.Generic;<br><br>namespace MyProject.Adapters.Interfaces<br>{<br>    public interface IBookRepository<br>    {<br>        List&lt;Book&gt; GetAll();<br>    }<br>}<br><br>// BookRepository.cs<br>using MyProject.Domain.Entities;<br>using MyProject.Adapters.Interfaces;<br>using System.Collections.Generic;<br><br>namespace MyProject.Adapters.Database<br>{<br>    public class BookRepository : IBookRepository<br>    {<br>        public List&lt;Book&gt; GetAll()<br>        {<br>            // retrieve list of books from database<br>            return new List&lt;Book&gt;()<br>            {<br>                new Book() { Id = 1, Title = &quot;Clean Code&quot;, Author = &quot;Robert C. Martin&quot;, Year = 2008 },<br>                new Book() { Id = 2, Title = &quot;The Pragmatic Programmer&quot;, Author = &quot;Andrew Hunt and David Thomas&quot;, Year = 1999 },<br>                new Book() { Id = 3, Title = &quot;Design Patterns&quot;, Author = &quot;Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides&quot;, Year = 1994 }<br>            };<br>        }<br>    }<br>}<br><br>// IBookService.cs<br>using MyProject.Domain.Entities;<br>using System.Collections.Generic;<br><br>namespace MyProject.Application.Interfaces<br>{<br>    public interface IBookService<br>    {<br>        List&lt;Book&gt; GetAllBooks();<br>    }<br>}<br><br>// BookService.cs<br>using MyProject.Domain.Entities;<br>using MyProject.Adapters.Interfaces;<br>using MyProject.Application.Interfaces;<br>using System.Collections.Generic;<br><br>namespace MyProject.Application.Services<br>{<br>    public class BookService : IBookService<br>    {<br>        private readonly IBookRepository _bookRepository;<br><br>        public BookService(IBookRepository bookRepository)<br>        {<br>            _bookRepository = bookRepository;<br>        }<br><br>        public List&lt;Book&gt; GetAllBooks()<br>        {<br>            return _bookRepository.GetAll();<br>        }<br>    }<br>}<br><br>// BooksController.cs<br>using Microsoft.AspNetCore.Mvc;<br>using MyProject.Application.Interfaces;<br><br>namespace MyProject.Adapters.RestApi.Controllers<br>{<br>    [Route(&quot;api/[controller]&quot;)]<br>    [ApiController]<br>    public class BooksController : ControllerBase<br>    {<br>        private readonly IBookService _bookService;<br><br>        public BooksController(IBookService bookService)<br>        {<br>            _bookService = bookService;<br>        }<br><br>        [HttpGet]<br>        public IActionResult GetBooks()<br>        {<br>            var books = _bookService.GetAllBooks();<br>            return Ok(books);<br>        }<br>    }<br>}</pre><p><strong><em>Pros of Hexagonal Architecture:</em></strong></p><ol><li><strong>Separation of concerns: </strong>Hexagonal Architecture separates the core business logic from the implementation details, which makes the codebase more modular and easier to maintain.</li><li><strong>Flexibility:</strong> Hexagonal Architecture makes it easier to swap out adapters and makes the codebase more flexible and extensible.</li><li><strong>Testability:</strong> Hexagonal Architecture makes it easier to test the codebase since the core business logic is isolated from the implementation details.</li></ol><p><strong><em>Cons of Hexagonal Architecture:</em></strong></p><ol><li><strong>Complexity:</strong> Hexagonal Architecture can be complex, especially for larger projects, which may require more granular separation of concerns.</li><li><strong>Over-engineering:</strong> Hexagonal Architecture can lead to over-engineering, where developers spend too much time on designing the architecture and not enough on delivering functionality.</li><li><strong>Additional overhead:</strong> Hexagonal Architecture introduces additional overhead in terms of the number of interfaces and classes required, which can increase the complexity of the codebase.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*KuCHg887yOJTIACs0hpOwA.gif" /></figure><p>In conclusion, both Clean Architecture and Hexagonal Architecture are software architecture patterns that aim to create maintainable, testable, and extensible software systems. Although both patterns share similar goals, they differ in their approach to structuring the project and how they achieve these goals.</p><p>Clean Architecture focuses on the independence of the layers, the data flow from the outer layers to the inner layers, and the ability to swap out dependencies without affecting the rest of the system.</p><p>On the other hand, Hexagonal Architecture is based on the separation of concerns between the domain and the infrastructure. This approach uses ports and adapters to define the functionality of the application and allows for the implementation details to be easily swapped out without affecting the rest of the system. Hexagonal Architecture focuses on the separation of concerns between the domain and the infrastructure, the use of ports to define the functionality of the application, and the ability to swap out adapters for different external systems.</p><p>Both Clean Architecture and Hexagonal Architecture have their strengths and weaknesses, and the choice of which pattern to use depends on the specific requirements of the project. Clean Architecture may be more suitable for projects with complex business rules, while Hexagonal Architecture may be more suitable for projects with complex integrations with external systems.</p><p>Overall, the adoption of a software architecture pattern such as Clean Architecture or Hexagonal Architecture can bring significant benefits to software development, including improved maintainability, testability, and flexibility. By following the principles of these patterns, developers can create high-quality software systems that are resilient to change and adaptable to evolving business requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b11a6833136e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CQRS And MediatR : Step-by-Step]]></title>
            <link>https://medium.com/@araxis/implementing-cqrs-with-mediatr-library-step-by-step-sample-code-2fde29a0afaf?source=rss-60cea8e190f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fde29a0afaf</guid>
            <category><![CDATA[mediatr]]></category>
            <category><![CDATA[mediator]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[cqrs]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Meisam Alifallhi]]></dc:creator>
            <pubDate>Sun, 05 Feb 2023 11:07:20 GMT</pubDate>
            <atom:updated>2023-02-11T17:35:14.712Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pp6G5uaadkbnKdAFazRzkg.png" /><figcaption>CQRS</figcaption></figure><p>Command-Query Responsibility Segregation (CQRS) is an architectural pattern that separates the responsibilities of reading and writing data into two separate components. By using CQRS, commands and queries can be separated which allows them to be developed independently with different performance requirements. This creates more flexibility when scaling applications as the developers are able to scale out the commands and queries individually according to the load of each one. In addition, this separation of concerns allows for any changes on either side to not affect each other.</p><p>The two components of CQRS are:</p><ul><li><strong>Command</strong>: A command is used to modify data and is typically executed by an action that a user performs.</li><li><strong>Query:</strong> A query is used to retrieve data and is typically executed by an action that displays data to the user.</li></ul><p><strong>What Is MediatR</strong></p><p><a href="https://github.com/jbogard/MediatR">MediatR</a> is an open-source library that provides a simple mediator pattern implementation to help developers write cleaner, more maintainable code. It helps developers create applications using the Command Query Responsibility Segregation (CQRS) pattern, which allows them to separate the responsibilities of sending and handling commands, as well as querying and retrieving data. MediatR simplifies the process of writing code for CQRS applications by providing an easy-to-use API for sending commands and queries. It also provides a way to register handlers for specific commands or queries, allowing developers to easily create custom logic for their applications.</p><p>In this article, we will walk through the steps to implement CQRS in a .NET application using the MediatR library.</p><p><strong>Step 1: Install MediatR NuGet Package</strong></p><p>The first step in implementing CQRS in a .NET application using the MediatR library is to install the MediatR NuGet package. To do this, open the Package Manager Console in Visual Studio and enter the following command:</p><pre>Install-Package MediatR</pre><p><strong>Step 2: Create a Command Class</strong></p><p>The next step is to create a command class. A command class is used to modify data in the system. A command class should implement the IRequest interface provided by the MediatR library. Here is a sample command class:</p><pre>public class CreateUserCommand : IRequest<br>{<br>    public string FirstName { get; set; }<br>    public string LastName { get; set; }<br>    public string Email { get; set; }<br>}</pre><p><strong>Step 3: Create a Command Handler Class</strong></p><p>The next step is to create a command handler class. The command handler class is responsible for executing the command. A command handler class should implement the IRequestHandler interface provided by the MediatR library and should have a constructor that takes in the dependencies it requires. Here is a sample command handler class:</p><pre>public class CreateUserCommandHandler : IRequestHandler&lt;CreateUserCommand&gt;<br>{<br>    private readonly IUserRepository _userRepository;<br>    public CreateUserCommandHandler(IUserRepository userRepository)<br>    {<br>        _userRepository = userRepository;<br>    }<br><br>    public async Task&lt;Unit&gt; Handle(CreateUserCommand request, CancellationToken cancellationToken)<br>    {<br>        var user = new User<br>        {<br>            FirstName = request.FirstName,<br>            LastName = request.LastName,<br>            Email = request.Email<br>        };<br><br>        await _userRepository.CreateUser(user);<br><br>        return Unit.Value;<br>    }<br>}</pre><p><strong>Step 4: Register the Command Handler in the Dependency Injection Container</strong></p><p>Next, we need to register the command handler in the dependency injection container. This can be done using the AddMediatR method provided by the MediatR library. Here is an example using the <em>Microsoft.Extensions.DependencyInjection</em> library:</p><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    services.AddMediatR(typeof(CreateUserCommandHandler).Assembly);<br>    services.AddTransient&lt;IUserRepository, UserRepository&gt;();<br>}</pre><p><strong>Step 5: Execute the Command</strong></p><p>Finally, we can execute the command by sending it to the mediator using the Send method provided by the MediatR library. Here is an example of executing the CreateUserCommand:</p><pre>var command = new CreateUserCommand<br>{<br>    FirstName = &quot;John&quot;,<br>    LastName = &quot;Doe&quot;,<br>    Email = &quot;john.doe@example.com&quot;<br>};<br><br>await _mediator.Send(command);</pre><p>In conclusion, CQRS is an architectural pattern that separates the responsibilities of reading and writing data into two separate components. The MediatR library provides a simple and efficient way to implement CQRS in a .NET application. By following the steps outlined in this article, you can easily implement CQRS in your .NET application using the MediatR library.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fde29a0afaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>