<?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 Kostiantyn Bilous on Medium]]></title>
        <description><![CDATA[Stories by Kostiantyn Bilous on Medium]]></description>
        <link>https://medium.com/@sharpassembly?source=rss-a27d5e81061b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8OKoqWoC9UYfj3qeCKgrMA.png</url>
            <title>Stories by Kostiantyn Bilous on Medium</title>
            <link>https://medium.com/@sharpassembly?source=rss-a27d5e81061b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 15:30:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sharpassembly/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[How to Handle Validation Checks in C# with MediatR and FluentValidation]]></title>
            <link>https://medium.com/sharpassembly/how-to-handle-validation-checks-in-c-with-mediatr-and-fluentvalidation-13a3da3eca14?source=rss-a27d5e81061b------2</link>
            <guid isPermaLink="false">https://medium.com/p/13a3da3eca14</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-design]]></category>
            <dc:creator><![CDATA[Kostiantyn Bilous]]></dc:creator>
            <pubDate>Tue, 18 Jun 2024 04:58:36 GMT</pubDate>
            <atom:updated>2024-06-18T05:20:19.485Z</atom:updated>
            <content:encoded><![CDATA[<p>In enterprise software development, maintaining clean and maintainable code is a non-functional requirement. One critical aspect of achieving this is effectively handling validation errors, especially in complex applications where separating concerns and adhering to principles like the <strong>Single Responsibility Principle (SRP)</strong> can significantly enhance overall code quality. This article will explore how to handle validation errors using <strong>FluentValidation</strong> and <strong>MediatR </strong>within a .NET application. By leveraging these libraries, we can ensure that application logic is robust, scalable, and easy to maintain.</p><p>Throughout this article, we will demonstrate how to implement validation logic for creating a new Party in the personal investment tracker application—<strong><em>InWestMan</em></strong>, ensuring that all necessary rules are enforced before the entity is persisted in the database.</p><h4>Validation in Software Development</h4><p>Validation is a fundamental aspect of software development, ensuring that data meets specific criteria before it is processed or stored. Proper validation helps prevent errors, maintain data integrity, and improve user experience by providing immediate feedback on incorrect inputs. There are various levels at which validation can be implemented, including at the domain level, application level, and even at the user interface level.</p><h4>The Single Responsibility Principle (SRP)</h4><p>The <strong>Single Responsibility Principle (SRP)</strong> is one of the <strong>SOLID</strong> principles of object-oriented design. It states that a class should have only one reason to change: one job or responsibility. By adhering to SRP, we can create more modular and maintainable code. In our example, separating validation logic from command handling logic helps us adhere to SRP, making our code cleaner and more testable.</p><h4>Introduction to FluentValidation</h4><p><a href="https://docs.fluentvalidation.net/en/latest/"><strong>FluentValidation</strong></a> is a popular .NET library for building strongly typed validation rules. It allows developers to define validation logic fluently and expressively, making the code easier to read and maintain. <strong>FluentValidation </strong>supports various validation scenarios, including synchronous and asynchronous validation, particularly useful for complex applications.</p><p>Key features of <strong>FluentValidation </strong>include:</p><ul><li><strong>Fluent API</strong>: Define validation rules using a fluent interface, which improves readability.</li><li><strong>Custom Validators</strong>: Create custom validation rules for specific business requirements.</li><li><strong>Asynchronous Validation</strong>: Support for asynchronous validation is crucial for validating data against external resources like databases.</li></ul><h4>Introduction to MediatR</h4><p><a href="https://github.com/jbogard/MediatR"><strong>MediatR</strong></a><strong> </strong>is a simple mediator library for .NET that facilitates the implementation of the mediator pattern. It helps decouple the sending of requests from handling them, promoting a more modular and maintainable architecture. Using <strong>MediatR</strong>, we can centralize the handling of commands, queries, and notifications, making managing complex workflows in an application more accessible.</p><p>Key features of <strong>MediatR </strong>include:</p><ul><li><strong>Decoupling</strong>: Decouples request sending from handling, promoting loose coupling between components.</li><li><strong>Pipeline Behaviors</strong>: Supports pipeline behaviors, allowing features like validation, logging, and caching to be handled centrally.</li><li><strong>Scalability</strong>: Scales well with complex applications by organizing request-handling logic in a structured way.</li></ul><h4>Combining <strong>FluentValidation</strong> and MediatR</h4><p>Combining <strong>FluentValidation </strong>and <strong>MediatR </strong>can achieve a robust validation mechanism within our .NET application. <strong>FluentValidation </strong>handles the validation logic, ensuring that all necessary rules are enforced, while <strong>MediatR </strong>manages the flow of commands and queries, decoupling the request sending from the handling process. This combination creates a clean, maintainable, and scalable architecture.</p><p>The following sections will explore a practical example of implementing validation for a <strong>Party</strong> entity in our application. We will demonstrate how to define validation rules using <strong>FluentValidation</strong>, integrate these rules with <strong>MediatR</strong>&#39;s command handling, and ensure that our application adheres to best practices in software development.</p><h4>Practical Example</h4><p>Let&#39;s look into the Party<strong> </strong>domain consists of the party name, country code, and party type properties. The <strong>Party</strong> is an <strong>Entity </strong>and an <strong>Aggregate Root</strong>; thus, it is stored and accessible through the repository.</p><pre>using Ardalis.GuardClauses;<br>using InWestMan.DomainEvents;<br>using InWestMan.Entities;<br>using InWestMan.Globals.Countries;<br>using InWestMan.Repositories;<br><br>public class Party : BaseEntity&lt;Guid&gt;, IAggregateRoot<br>{<br>    private Party() // EF constructor<br>    {<br>    }<br><br>    public Party(string name, CountryCode countryCode, PartyType type)<br>    {<br>        Guard.Against.NullOrWhiteSpace(name, nameof(name));<br>        Guard.Against.Null(type, nameof(type));<br><br>        Name = name;<br>        CountryCode = countryCode;<br>        Type = type;<br>    }<br><br>    public string Name { get; set; } = string.Empty;<br>    public CountryCode CountryCode { get; set; }<br>    public PartyType Type { get; set; }<br><br>    public override string ToString()<br>    {<br>        return Name;<br>    }<br>}</pre><p>To add a new Party to DB, we must create an AddPartyCommand, which implements <strong>MediatR&#39;s</strong> IRequest&lt;&gt; interface.</p><pre>using FluentResults;<br>using InWestMan.Globals.Countries;<br>using MediatR;<br><br>public class AddPartyCommand : IRequest&lt;Result&lt;Guid&gt;&gt;<br>{<br>    public required string Name { get; init; }<br>    public required CountryCode CountryCode { get; init; }<br>    public required PartyType Type { get; init; }<br>}</pre><p>According to the command domain logic, the command requires the party name, country code, and party type to be specified. After executing the command, it returns a result with the <strong>GUID </strong>of a newly created party.</p><p>Consequently, the AddPartyCommandHandler implements the logic of how the AddPartyCommand should be executed.</p><pre>using FluentResults;<br>using InWestMan.MultiTenancy;<br>using InWestMan.Repositories;<br>using MediatR;<br>using Microsoft.Extensions.Logging;<br><br>public class AddPartyCommandHandler : IRequestHandler&lt;AddPartyCommand, Result&lt;Guid&gt;&gt;<br>{<br>    private readonly ILogger&lt;AddPartyCommand&gt; _logger;<br>    private readonly IMultiTenancyService _multiTenancyService;<br>    private readonly IRepository&lt;Party&gt; _repository;<br><br>    public AddPartyCommandHandler(IRepository&lt;Party&gt; repository, ILogger&lt;AddPartyCommand&gt; logger,<br>        IMultiTenancyService multiTenancyService)<br>    {<br>        _repository = repository;<br>        _logger = logger;<br>        _multiTenancyService = multiTenancyService;<br>    }<br><br>    public async Task&lt;Result&lt;Guid&gt;&gt; Handle(AddPartyCommand request, CancellationToken cancellationToken)<br>    {<br>        try<br>        {<br>            _logger.LogInformation($&quot;Creating new Party in InWestMan database: {request.Name}&quot;);<br><br>            var party = new Party(request.Name, request.CountryCode, request.Type);<br>            party.AddTenantId(_multiTenancyService.CurrentTenant);<br>            await _repository.AddAsync(party, cancellationToken);<br><br>            _logger.LogInformation($&quot;New Party in InWestMan database is created: {request.Name}&quot;);<br><br>            return Result.Ok(party.Id);<br>        }<br>        catch (Exception ex)<br>        {<br>            return Result.Fail&lt;Guid&gt;(ex.Message);<br>        }<br>    }<br>}</pre><p>In the command handler implementation, we log the start and end of the new party creation process, create a new <strong>Party </strong>domain, and add it to the repository. In the success case, we return the new <strong>Party&#39;s </strong>GUID inside the Result&lt;Guid&gt; object. In the case of an exception, we wrap the code in the try-catch block and return the <strong>Exception </strong>message as an error message for the failed <strong>Result</strong> object.</p><p>You can read more about the <strong>Result</strong> <strong>Pattern</strong> in my Medium article below:</p><p><a href="https://medium.com/sharpassembly/mediatr-response-should-the-request-handler-return-exceptions-8a7928a7c572">MediatR Response: Should the Request Handler Return Exceptions?</a></p><p>Now, let&#39;s switch to validation. As you probably have seen, we already have some basic input validations in the <strong>Party</strong> domain class; besides, I would like a more robust validation on the application level. I want to check that the user is not trying to create a Party with the same name. Indeed, I can add this logic in the <strong>Command Handler</strong>, but I would like to separate concerns and adhere to the <strong>Single Responsibility Principle (SRP)</strong>. Thus, I plan to use the <strong>FluentValidation </strong>library to create an AddPartyCommandValidator.</p><pre>using FluentValidation;<br>using InWestMan.Parties.Specifications;<br>using InWestMan.Repositories;<br><br>namespace InWestMan.Parties.Commands.AddParty;<br><br>public class AddPartyCommandValidator : AbstractValidator&lt;AddPartyCommand&gt;<br>{<br>    private readonly IReadRepository&lt;Party&gt; _partyRepository;<br><br>    public AddPartyCommandValidator(IReadRepository&lt;Party&gt; partyRepository)<br>    {<br>        _partyRepository = partyRepository;<br><br>        RuleFor(x =&gt; x.Name)<br>            .NotEmpty().WithMessage(&quot;Name is required.&quot;)<br>            .Length(1, 100).WithMessage(&quot;Name must be between 1 and 100 characters.&quot;)<br>            .MustAsync(BeUniqueName).WithMessage(&quot;The party with the same name already exists&quot;);<br><br>        RuleFor(x =&gt; x.CountryCode)<br>            .IsInEnum().WithMessage(&quot;Invalid country code.&quot;);<br><br>        RuleFor(x =&gt; x.Type)<br>            .IsInEnum().WithMessage(&quot;Invalid party type.&quot;);<br>    }<br><br>    private async Task&lt;bool&gt; BeUniqueName(string name, CancellationToken cancellationToken)<br>    {<br>        var partyByNameSpecification = new PartyByNameSpecification(name);<br>        return !await _partyRepository.AnyAsync(partyByNameSpecification, cancellationToken);<br>    }<br>}</pre><p>There, we validate each property of AddPartyCommand separately by specifying validation rules. We check that enum values are within the range of the enum type, and what is more important is that the name is not empty, its length is between 1 and 100 characters, and it is unique in the repository.</p><p>Now, I need to set my <strong>MediatR&#39;s</strong> command execution so that the validator validates the command before executing the command handler. For this, I will create a new general <strong>MediatR&#39;s</strong> <strong>Pipeline Behavior</strong>, executing all validators associated with the specific command before command handler execution.</p><pre>using FluentResults;<br>using FluentValidation;<br>using FluentValidation.Results;<br>using MediatR;<br>using Microsoft.Extensions.Logging;<br>using Newtonsoft.Json;<br><br>namespace InWestMan.PipelineBehaviors;<br><br>public class ValidationBehavior&lt;TRequest, TResponse&gt; : IPipelineBehavior&lt;TRequest, TResponse&gt;<br>    where TRequest : class, IRequest&lt;TResponse&gt;<br>    where TResponse : class<br>{<br>    private readonly bool _hasValidators;<br>    private readonly ILogger&lt;ValidationBehavior&lt;TRequest, TResponse&gt;&gt; _logger;<br>    private readonly IEnumerable&lt;IValidator&lt;TRequest&gt;&gt; _validators;<br><br>    public ValidationBehavior(IEnumerable&lt;IValidator&lt;TRequest&gt;&gt; validators, ILogger&lt;ValidationBehavior&lt;TRequest, TResponse&gt;&gt; logger)<br>    {<br>        _validators = validators;<br>        _logger = logger;<br>        _hasValidators = _validators.Any();<br>    }<br><br>    public async Task&lt;TResponse&gt; Handle(TRequest request, RequestHandlerDelegate&lt;TResponse&gt; next, CancellationToken cancellationToken)<br>    {<br>        _logger.LogTrace(&quot;Handling {RequestType}&quot;, typeof(TRequest).Name);<br><br>        if (!_hasValidators)<br>        {<br>            _logger.LogTrace(&quot;No validators configured for {RequestType}&quot;, typeof(TRequest).Name);<br>            return await next();<br>        }<br><br>        var context = new ValidationContext&lt;TRequest&gt;(request);<br>        ValidationResult[] validationResults = <br>                    await Task.WhenAll(_validators.Select(v =&gt; <br>                           v.ValidateAsync(context, cancellationToken)));<br><br>        List&lt;ValidationFailure&gt; failures = <br>                    validationResults.SelectMany(r =&gt; r.Errors)<br>                          .Where(f =&gt; f != null).ToList();<br><br>        if (!failures.Any())<br>        {<br>            _logger.LogTrace(&quot;Validation passed for {RequestType}&quot;, typeof(TRequest).Name);<br>            return await next();<br>        }<br><br>        var errorJson = JsonConvert.SerializeObject(failures);<br>        _logger.LogWarning(&quot;Validation failed for {RequestType}: {Errors}&quot;, typeof(TRequest).Name, errorJson);<br><br>        if (IsResultType(typeof(TResponse)))<br>            return (dynamic)Result.Fail(errorJson);<br><br>        throw new ValidationException(failures);<br>    }<br><br>    private static bool IsResultType(Type responseType)<br>    {<br>        return responseType == typeof(Result) ||<br>               (responseType.IsGenericType<br>                &amp;&amp; responseType.GetGenericTypeDefinition() == typeof(Result&lt;&gt;));<br>    }<br>}</pre><p>Now, this is one of the most complicated parts. When a new command is sent to a <strong>MediatR</strong> for handling, it previously goes through the ValidationBehavior pipeline. At first, it checks if the command has any validators associated with it. If yes, it executes all validators and waits for the results. In the case of any failure, it checks if the command response is a Result type to create a new failed Result object. If not, the ValidationException will be thrown.</p><p>The last thing we must do is register in the service collection <strong>Dependency Injection (DI) </strong>container.</p><pre>using FluentValidation;<br>using InWestMan.PipelineBehaviors;<br>using MediatR;<br>using Microsoft.Extensions.DependencyInjection;<br><br>namespace InWestMan;<br><br>public static class ApplicationServiceRegistration<br>{<br>    public static IServiceCollection AddApplicationServices(this IServiceCollection services)<br>    {<br>        services.AddMediatR(cfg =&gt; cfg.RegisterServicesFromAssemblies(AppDomain.CurrentDomain.GetAssemblies()));<br>        services.AddScoped(typeof(IPipelineBehavior&lt;,&gt;), typeof(ValidationBehavior&lt;,&gt;));<br>        services.AddValidatorsFromAssemblies(AppDomain.CurrentDomain.GetAssemblies());<br><br>        return services;<br>    }<br>}</pre><p>We add <strong>MediatR</strong> with all Requests in the assembly, ValidationBehavior, and all <strong>FluentValidation </strong>classes.</p><h4>Conclusion</h4><p>Effectively handling validation errors is crucial to maintaining an application&#39;s integrity and reliability. Using <strong>FluentValidation </strong>and <strong>MediatR</strong>, we can create a clean and maintainable architecture, ensuring that validation logic is robust and separate from business logic. This approach adheres to the <strong>Single Responsibility Principle (SRP)</strong> and enhances an application&#39;s modularity and scalability.</p><p>Using these tools, we can handle validation errors more effectively, provide immediate feedback to users, and ensure that only valid data is processed and stored. This improves the user experience and helps maintain the integrity of the application&#39;s data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IwrZiOaPbaM1tnTk" /><figcaption>Credits: DALL·E generated</figcaption></figure><p><strong>Subscribe for more insights and in-depth analysis:</strong></p><ul><li><a href="https://sharpassembly.medium.com/">SharpAssembly on Medium</a></li><li><a href="https://dev.to/sharpassembly">SharpAssembly on Dev.to</a></li><li><a href="https://t.me/SharpAssembly">SharpAssembly on Telegram</a></li></ul><p>#SOLID #CQRS #DDD #InWestMan</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13a3da3eca14" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sharpassembly/how-to-handle-validation-checks-in-c-with-mediatr-and-fluentvalidation-13a3da3eca14">How to Handle Validation Checks in C# with MediatR and FluentValidation</a> was originally published in <a href="https://medium.com/sharpassembly">SharpAssembly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MediatR Response: Should the Request Handler Return Exceptions?]]></title>
            <link>https://medium.com/sharpassembly/mediatr-response-should-the-request-handler-return-exceptions-8a7928a7c572?source=rss-a27d5e81061b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a7928a7c572</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Kostiantyn Bilous]]></dc:creator>
            <pubDate>Thu, 02 May 2024 14:08:26 GMT</pubDate>
            <atom:updated>2024-05-02T14:08:26.578Z</atom:updated>
            <content:encoded><![CDATA[<p>In the evolving landscape of software architecture, the choice between traditional exception handling and adhering to functional programming principles to manage errors directly impacts system design and reliability.</p><p>Clean architecture advocates for systems independent of frameworks, UI, databases, and external agencies. This independence is crucial for maintaining the system’s integrity over time. In line with this, exceptions — traditionally used to handle unforeseen errors — should be reserved for circumstances outside the application’s normal functioning. However, the debate continues on how to handle predictable errors and validations.</p><p>On one side, proponents of thin controllers in architectures argue that the business logic should be encapsulated away from the API layer, making the API layer as lean as possible. This approach typically leads to handling exceptions at the middleware or framework level, thus maintaining a separation of concerns where controllers focus solely on routing and minimal preprocessing.</p><p>Conversely, functional programming offers an alternative by emphasizing immutability and pure functions, which leads to systems that are easier to reason about and test. Here, errors are treated as first-class citizens, taking the form of predictable results rather than as exceptions. This method suggests that all possible outcomes — including errors — are part of a function’s expected result, encapsulated in types like Result, which can explicitly represent success or failure states without throwing exceptions.</p><p>Both methodologies aim to reduce side effects and enhance system robustness, yet they employ fundamentally different approaches to achieve these objectives. This article will compare these two paradigms by implementing the creation of a Bank Account, where domain validations ensure the account’s name and associated bank are valid. We will explore exception handling at the API and application layers using NuGet packages like Ardalis.GuardClauses for assertions that throw ArgumentExceptions if the domain validation rules are violated and employing MediatR and FluentResults to handle operation outcomes in a more functional style.</p><p>Read more about MediatR tool in the article below:</p><p><a href="https://medium.com/sharpassembly/cqrs-repository-and-mediatr-65883d1a1fac">CQRS, Repository, and MediatR in .NET</a></p><h3>Two Approaches to Handling Exceptions</h3><p>For example, we will implement the creation and persistence of a new Bank Account domain entity from a personal investment tracking application, InWestMan, using two approaches to exception handling: <strong>Middleware-Based Error Handling</strong> at the API layer and <strong>Result Pattern</strong> at the application layer.</p><p>Upon creation and reconstitution, the Bank Account domain checks that its name is not blank and is associated with a bank. If the check fails, the domain object will throw an ArgumentException. For this purpose, I use Ardalis.GuardClauses NuGet package, which simplifies the domain validations.</p><pre>using Ardalis.GuardClauses;<br>using InWestMan.DomainEvents;<br>using InWestMan.Globals.Currencies;<br>using InWestMan.Parties;<br><br>namespace InWestMan.Assets.BankAccounts;<br><br>public class BankAccount : Asset<br>{<br>    private BankAccount() { }<br><br>    public BankAccount(string name, Guid bankId, CurrencyCode currencyCode) : base(name, currencyCode)<br>    {<br>        Guard.Against.NullOrWhiteSpace(name, nameof(Name)); //throws ArgumentException<br>        Guard.Against.Null(bankId, nameof(BankId)); //throws ArgumentException<br>        Name = name;<br>        BankId = bankId;<br>    }<br><br>    public Party Bank { get; set; } = null!;<br>    public Guid BankId { get; set; }<br><br>    public void UpdateBank(Guid bankId)<br>    {<br>        Guard.Against.NullOrEmpty(bankId, nameof(BankId)); //throws ArgumentException<br>        if (!BankId.Equals(bankId))<br>        {<br>            BankId = bankId;<br>            Events.Add(new EntityFieldUpdated&lt;BankAccount&gt;(nameof(BankId), bankId.ToString()));<br>        }<br>    }<br>}</pre><h4>#1. Middleware-Based Error Handling</h4><p>At the application layer, the Create command is designed to generate a new bank account entity, save it in the database, and return a unique identifier (GUID) of this bank account. This is reflected in the structured AddBankAccountCommand, which requires specific details such as the account name, currency code, and associated bank ID, each marked as required to ensure data integrity immediately.</p><pre>public class AddBankAccountCommand : IRequest&lt;Guid&gt;<br>{<br>    [Required] public string Name { get; set; } = string.Empty;<br><br>    [Required] public CurrencyCode CurrencyCode { get; set; }<br><br>    [Required] public Guid BankId { get; set; }<br>}</pre><p>The handler for this command, AddBankAccountCommandHandler, is tasked with validating the request against existing records to prevent duplications using a domain-specific specification. If duplication is detected, it throws a ValidationException, creating unique bank accounts. This validation process is essential for maintaining data consistency and reliability within the system.</p><pre>using System.ComponentModel.DataAnnotations;<br>using InWestMan.Assets.BankAccounts.Specifications;<br>using InWestMan.Repositories;<br>using MediatR;<br><br>namespace InWestMan.Assets.BankAccounts.Commands.AddBankAccount;<br><br>public class AddBankAccountCommandHandler : IRequestHandler&lt;AddBankAccountCommand, Guid&gt;<br>{<br>    private readonly IRepository&lt;BankAccount&gt; _repository;<br><br>    public AddBankAccountCommandHandler(IRepository&lt;BankAccount&gt; repository)<br>    {<br>        _repository = repository;<br>    }<br><br>    public async Task&lt;Guid&gt; Handle(AddBankAccountCommand request, CancellationToken cancellationToken)<br>    {<br>        var bankAccountByNameSpecification = new BankAccountByNameSpecification(request.Name);<br>        if (await _repository.AnyAsync(bankAccountByNameSpecification, cancellationToken))<br>            throw new ValidationException(&quot;The bank account with the same name already exists.&quot;);<br><br>        var newBankAccount = new BankAccount(request.Name, request.BankId, request.CurrencyCode);<br><br>        await _repository.AddAsync(newBankAccount, cancellationToken);<br><br>        return newBankAccount.Id;<br>    }<br>}</pre><p>In the corresponding controller method, the API layer handles the client’s POST request by mapping the incoming DTO AddBankAccountCommandand dispatching it using MediatR. The result, which includes the newly created bank account’s GUID, is then returned to the client, facilitating a responsive and interactive user experience.</p><pre>    [HttpPost]<br>    [ProducesResponseType(StatusCodes.Status201Created)]<br>    [ProducesDefaultResponseType]<br>    public async Task&lt;ActionResult&lt;Guid&gt;&gt; Create([FromBody] CreateBankAccountDto createDto)<br>    {<br>        var command = _mapper.Map&lt;AddBankAccountCommand&gt;(createDto);<br>        var commandResult = await _mediator.Send(command);<br><br>        return CreatedAtAction(nameof(GetById), new { id = commandResult }, commandResult);<br>    }</pre><p>Transitioning to error handling, we employ middleware to intercept and transform exceptions into structured HTTP responses. This middleware ensures that all unhandled exceptions are caught and appropriately formatted before being sent back to the client, thus safeguarding the API from leaking sensitive error details and providing a consistent error-handling mechanism across the application.</p><pre>using System.ComponentModel.DataAnnotations;<br>using System.Net;<br>using System.Text.Json;<br><br>namespace InWestMan.Middlewares;<br><br>public class ExceptionHandlerMiddleware<br>{<br>    private readonly RequestDelegate _next;<br><br>    public ExceptionHandlerMiddleware(RequestDelegate next)<br>    {<br>        _next = next;<br>    }<br><br>    public async Task Invoke(HttpContext context)<br>    {<br>        try<br>        {<br>            await _next(context);<br>        }<br>        catch (Exception ex)<br>        {<br>            await ConvertException(context, ex);<br>        }<br>    }<br><br>    private Task ConvertException(HttpContext context, Exception exception)<br>    {<br>        var httpStatusCode = HttpStatusCode.InternalServerError;<br><br>        context.Response.ContentType = &quot;application/json&quot;;<br><br>        var result = string.Empty;<br><br>        switch (exception)<br>        {<br>            case ValidationException validationException:<br>                httpStatusCode = HttpStatusCode.BadRequest;<br>                result = JsonSerializer.Serialize(validationException.ValidationResult.ErrorMessage);<br>                break;<br>            case ArgumentException argumentException:<br>                httpStatusCode = HttpStatusCode.BadRequest;<br>                result = JsonSerializer.Serialize(argumentException.Message);<br>                break;<br>            case BadRequestException badRequestException:<br>                httpStatusCode = HttpStatusCode.BadRequest;<br>                result = badRequestException.Message;<br>                break;<br>            case NotFoundException:<br>                httpStatusCode = HttpStatusCode.NotFound;<br>                break;<br>            case not null:<br>                httpStatusCode = HttpStatusCode.BadRequest;<br>                break;<br>        }<br><br>        context.Response.StatusCode = (int)httpStatusCode;<br><br>        if (result == string.Empty) result = JsonSerializer.Serialize(new { error = exception?.Message });<br><br>        return context.Response.WriteAsync(result);<br>    }<br>}</pre><p>Finally, the custom-created error-handling middleware should be registered in the application pipeline configuration.</p><pre>builder.UseMiddleware&lt;ExceptionHandlerMiddleware&gt;();</pre><h4>#2. Adopting the Result Pattern</h4><p>At the application layer, our approach significantly shifts as we adopt the Result pattern, utilizing the FluentResults NuGet package to enhance our error-handling strategy. This method alters the expected output of our commands from a simple GUID to a Result&lt;Guid&gt;. Such a transformation encapsulates the outcome of command execution within a structured result, offering more granular control over error handling, which neatly complies with our business logic requirements.</p><pre>public class AddBankAccountCommand : IRequest&lt;Result&lt;Guid&gt;&gt;<br>{<br>    [Required] public string Name { get; set; } = string.Empty;<br><br>    [Required] public CurrencyCode CurrencyCode { get; set; }<br><br>    [Required] public Guid BankId { get; set; }<br>}</pre><p>In implementing this pattern, the AddBankAccountCommandHandler in the Application layer plays a crucial role. It processes the creation requests and directly integrates error handling into the workflow using the Result pattern. This allows for immediate feedback on the operation’s success or failure and the communication of specific error messages directly related to the business rules, enhancing user experience and system reliability.</p><pre>using FluentResults;<br>using InWestMan.Assets.BankAccounts.Specifications;<br>using InWestMan.Repositories;<br>using MediatR;<br><br>namespace InWestMan.Assets.BankAccounts.Commands.AddBankAccount;<br><br>public class AddBankAccountCommandHandler : IRequestHandler&lt;AddBankAccountCommand, Result&lt;Guid&gt;&gt;<br>{<br>    private readonly IRepository&lt;BankAccount&gt; _repository;<br><br>    public AddBankAccountCommandHandler(IRepository&lt;BankAccount&gt; repository)<br>    {<br>        _repository = repository;<br>    }<br><br>    public async Task&lt;Result&lt;Guid&gt;&gt; Handle(AddBankAccountCommand request, CancellationToken cancellationToken)<br>    {<br>        try<br>        {<br>            var bankAccountByNameSpecification = new BankAccountByNameSpecification(request.Name);<br>            if (await _repository.AnyAsync(bankAccountByNameSpecification, cancellationToken))<br>                return Result.Fail(&quot;The bank account with the same name already exists.&quot;);<br><br>            var newBankAccount = new BankAccount(request.Name, request.BankId, request.CurrencyCode);<br><br>            await _repository.AddAsync(newBankAccount, cancellationToken);<br><br>            return Result.Ok(newBankAccount.Id);<br>        }<br>        catch (ArgumentException ex)<br>        {<br>            return Result.Fail(ex.Message);<br>        }<br>    }<br>}</pre><p>Transitioning to the controller level, the Create Bank Account Controller method adapts to accommodate the Result pattern. Instead of merely returning a GUID, it now handles the Result object, facilitating a response mechanism that directly reflects the outcome of the command — either confirming successful account creation or detailing the reasons for failure.</p><pre>    [HttpPost]<br>    [ProducesResponseType(StatusCodes.Status201Created)]<br>    [ProducesDefaultResponseType]<br>    public async Task&lt;ActionResult&lt;Guid&gt;&gt; Create([FromBody] CreateBankAccountDto createDto)<br>    {<br>        var command = _mapper.Map&lt;AddBankAccountCommand&gt;(createDto);<br>        var commandResult = await _mediator.Send(command);<br>        if (commandResult.IsFailed)<br>        {<br>            return BadRequest(commandResult.Errors);<br>        }<br><br>        return CreatedAtAction(nameof(GetById), new { id = commandResult.Value }, commandResult.Value );<br>    }</pre><p>With the adoption of this comprehensive Result pattern, the necessity for custom exception-handling middleware diminishes. All potential exceptions and errors are addressed directly within the Application layer, obviating the need for middleware to catch and reformat exceptions. This results in a cleaner architecture that reduces overhead and enhances clarity and maintainability by localizing error handling within the context where it is most relevant.</p><h3>Conclusion: Choosing the Error Handling Strategy</h3><p>In software architecture, error-handling strategies are pivotal in defining the system’s robustness and clarity. Comparing the two approaches discussed—middleware-based exception handling versus the application layer result pattern—reveals distinct advantages and considerations for each, informing their appropriate use cases.</p><h4><strong>API Layer: Middleware-Based</strong></h4><p>This approach centralizes error management in the middleware, abstracting it away from the business logic.</p><p><em>Pros:</em></p><ul><li><strong>Centralization of Error Handling:</strong> This method simplifies the control flow by managing exceptions centrally, making it easier to handle unanticipated errors uniformly across various application parts.</li><li><strong>Simplicity in Implementation:</strong> Developers can implement and modify error-handling strategies without touching the business logic, promoting a cleaner separation of concerns.</li></ul><p><em>Cons:</em></p><ul><li><strong>Potential for Overuse:</strong> There’s a risk of using exceptions for control flow, which can lead to systems where exceptions are thrown for expected, non-exceptional conditions, potentially impacting performance.</li><li><strong>Decreased Transparency:</strong> As exceptions bubble up to the middleware, it might obscure the source and context of errors, making debugging more challenging.</li></ul><p><em>Use Cases:</em></p><ul><li>It is ideal for applications requiring a uniform way to handle unanticipated or external system errors, such as failures in external services or database issues.</li></ul><h4><strong>Application Layer</strong>:<strong> Result Pattern</strong></h4><p>Employing a result pattern at the application layer treats errors as expected outcomes, handled via types that explicitly represent success or failure.</p><p><em>Pros:</em></p><ul><li><strong>Enhanced Error Clarity:</strong> This approach treats errors as regular values, avoiding the pitfalls of exception handling for control flow and making error states explicit and predictable.</li><li><strong>Better Alignment with Functional Principles:</strong> It promotes immutability and function purity, making the system easier to reason about and test.</li></ul><p><em>Cons:</em></p><ul><li><strong>Increased Complexity:</strong> Requires more initial setup and can complicate the API with additional result-checking code.</li><li><strong>Potential for Duplication:</strong> Handling errors explicitly in each function might lead to repetitive error handling code unless carefully managed.</li></ul><p><em>Use Cases:</em></p><ul><li>It is particularly suitable for domains where business rules are complex and errors are a regular, expected part of operations, such as financial applications or systems with complex input validation needs.</li></ul><p>In conclusion, a project’s requirements and constraints should guide the choice between these error-handling strategies. Middleware-based exception handling might be more appropriate for applications where unexpected errors from external systems dominate. In contrast, an application layer result pattern fits scenarios requiring fine-grained control over business rules and where mistakes are as informative as successful outcomes. Both approaches can coexist within a clean architecture, chosen based on different aspects or layers of the application to optimize clarity, maintainability, and functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vVJqziyAu4Ywa44-idOITA.png" /><figcaption>Credits: DALL·E generated</figcaption></figure><p><strong>Subscribe for more insights and in-depth analysis:</strong></p><ul><li><a href="https://sharpassembly.medium.com/">SharpAssembly on Medium</a></li><li><a href="https://dev.to/sharpassembly">SharpAssembly on Dev.to</a></li><li><a href="https://t.me/SharpAssembly">SharpAssembly on Telegram</a></li></ul><p>#DDD #InWestMan</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a7928a7c572" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sharpassembly/mediatr-response-should-the-request-handler-return-exceptions-8a7928a7c572">MediatR Response: Should the Request Handler Return Exceptions?</a> was originally published in <a href="https://medium.com/sharpassembly">SharpAssembly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-step Guide to Implementing Multi-Tenancy in WebAPI Using ASP.NET Core Identity]]></title>
            <link>https://medium.com/sharpassembly/step-by-step-guide-to-implementing-multi-tenancy-in-webapi-using-asp-net-core-identity-f11b3bf88c56?source=rss-a27d5e81061b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f11b3bf88c56</guid>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Kostiantyn Bilous]]></dc:creator>
            <pubDate>Thu, 22 Feb 2024 05:33:08 GMT</pubDate>
            <atom:updated>2024-02-22T05:33:08.040Z</atom:updated>
            <content:encoded><![CDATA[<p>Building web applications for financial services requires a keen focus on security and scalability. One key challenge is managing and protecting client data while serving multiple clients from a single application instance. Multi-tenancy offers a solution by allowing a single application to serve different clients, or “tenants,” thereby keeping their data isolated and secure.</p><p>Implementing a multi-tenant model in <strong>ASP.NET Core</strong>, with <strong>ASP.NET Core Identity</strong> managing user authentication and authorization, requires specific steps that we will discuss below.</p><h3>Multi-Tenancy: An Overview</h3><p>Multi-tenancy is commonly seen in cloud computing and <strong>SaaS (Software as a Service)</strong> applications, enabling efficient resource utilization, simplified application management, and reduced operational costs. Multi-tenancy’s complexity and implementation requirements vary depending on the application’s needs.</p><h4>Types of Multi-Tenancy</h4><ol><li><strong>Single-Tenant Architecture: </strong>Each tenant has a dedicated instance of the software and underlying infrastructure. While not multi-tenancy in the strict sense, it’s often discussed in contrast to actual multi-tenant architectures.</li><li><strong>Separate Database: </strong>Tenants are separated into different databases with a single application instance. This keeps data separate and requires a new database environment for each new tenant.</li><li><strong>Shared Database, Separate Schemas:</strong> Tenants share the same database but have their own schemas and tables. This keeps data separate but within the same database environment.</li><li><strong>Shared Database, Shared Schema:</strong> The most complex form of multi-tenancy, where all tenants share the same database and schema. Tenant-specific identifiers differentiate data within the tables but require careful implementation to ensure data isolation.</li></ol><h4>Benefits of Multi-Tenancy</h4><ul><li><strong>Cost Efficiency: </strong>Sharing resources among tenants helps reduce hardware and software costs.</li><li><strong>Ease of Maintenance:</strong> Updates and patches must be applied to only one application instance, simplifying maintenance.</li><li><strong>Scalability:</strong> Scaling a single application instance is more manageable than maintaining multiple instances for each tenant.</li><li><strong>Resource Utilization:</strong> Multi-tenancy can result in more efficient resource use, as idle capacity can be reallocated.</li></ul><h4>Drawbacks of Multi-Tenancy</h4><ul><li><strong>Complexity:</strong> Implementing a multi-tenant architecture, particularly ensuring data isolation and security, can be complex.</li><li><strong>Performance Risks:</strong> Resource contention among tenants can impact performance.</li><li><strong>Security Concerns:</strong> Maintaining data isolation when using shared resources requires strict security measures to prevent potential data leaks and meet regulatory requirements.</li><li><strong>Customization Limitations: </strong>Providing deep customization options to tenants poses more challenges in a shared environment.</li></ul><h3>Practical example</h3><p>Now, let’s dive into a practical example from <strong><em>InWestMan</em></strong>, a software application for tracking personal investments that requires isolating sensitive client data to be accessible only to users who created them. In the example, we will add multitenancy support to ensure clients can access and manipulate only portfolios created by them. We will use the last multi-tenancy type, “<strong>Shared Database, Shared Schema</strong>,” using <strong>ASP.NET Core Identity</strong>.</p><p>1. First, in our <strong>Infrastructure</strong> project, we switch to using <strong>ASP.NET Core Identity’s</strong> DbContext, which includes all required identity models, by changing the inheritance of our AppDbContext from the basic <strong>Entity Framework’s</strong> DbContext to IdentityDbContext.</p><pre>public class AppDbContext : IdentityDbContext </pre><p>2. Next, in our <strong>WebAPI </strong>project, we need to register the <strong>Identity </strong>service in the Program.cs file.</p><pre>services.AddIdentity&lt;IdentityUser, IdentityRole&gt;()<br>            .AddEntityFrameworkStores&lt;AppDbContext&gt;();</pre><p>3. Subsequently, in our <strong>Domain </strong>project, we add a TenantId property to <strong>Aggregate Roots</strong>, which, according to our domain model, are sensitive, for example, a Portfolio entity that stores the client’s Positions.</p><p><a href="https://sharpassembly.medium.com/entity-value-object-and-aggregate-root-in-domain-driven-design-0ce9402e4ad3">Entity, Value Object, and Aggregate Root in Domain-Driven Design</a></p><pre>public abstract class BaseEntityWithMultitenancy&lt;TId&gt;<br>{<br>    public List&lt;BaseDomainEvent&gt; Events = [];<br><br>    public string TenantId { get; set; } = string.Empty;<br><br>    public TId Id { get; set; } = default!;<br>}</pre><pre>public class Portfolio : BaseEntityWithMultitenancy&lt;Guid&gt;, IAggregateRoot<br>{<br>    public string Name { get; set; } = string.Empty;<br>    public ICollection&lt;Position&gt; Positions { get; set; } = new List&lt;Position&gt;();<br><br>    // other logic and sensitive fields...<br>}</pre><p>4. Furthermore, in the <strong>Application </strong>project, we need to create MultiTenancyService that will keep a current tenant in the scope of the WebAPI call.</p><pre>public interface IMultiTenancyService<br>{<br>    string CurrentTenant { get; }<br>    void SetCurrentTenant(string tenant);<br>}</pre><pre>public class MultiTenancyService : IMultiTenancyService<br>{<br>    private string _tenant = string.Empty;<br><br>    public string CurrentTenant<br>    {<br>        get =&gt; _tenant;<br>        private set<br>        {<br>            if (_tenant != value)<br>            {<br>                var oldTenant = _tenant;<br>                _tenant = value;<br>            }<br>        }<br>    }<br><br>    public void SetCurrentTenant(string tenant)<br>    {<br>        if (string.IsNullOrWhiteSpace(tenant))<br>            throw new ArgumentException(&quot;CurrentTenant cannot be null or whitespace.&quot;, nameof(tenant));<br>        CurrentTenant = tenant;<br>    }<br>}</pre><p>5. It is crucial to remember to register the new MultiTenancyService in the service collection in the Program.cs file in the <strong>WebAPI </strong>project.</p><pre>services.AddScoped(typeof(IMultiTenancyService), typeof(MultiTenancyService));</pre><p>6. Now, let’s return to our <strong>Application </strong>project. I utilize the MediatR’s<strong> </strong>AddPortfolioCommand to add a new Portfolio to the database; therefore, I need to update my AddPortfolioHandler<strong> </strong>to include the client’s tenant when saving the created entity. To achieve this, I pass an IMultiTenancyService instance to my AddPortfolioHandler class and explicitly assign the current TenantId to the newly created Portfolio object before saving.</p><p><a href="https://sharpassembly.medium.com/cqrs-repository-and-mediatr-65883d1a1fac">CQRS, Repository, and MediatR</a></p><pre>public class AddPortfolioCommand : IRequest&lt;Result&lt;Guid&gt;&gt;<br>{<br>    public string Name { get; set; }<br>    public CurrencyCode CurrencyCode { get; set; }<br>}</pre><pre>public class AddPortfolioHandler : IRequestHandler&lt;AddPortfolioCommand, Result&lt;Guid&gt;&gt;<br>{<br>    private readonly IMultiTenancyService _multiTenancyService;<br>    private readonly IRepository&lt;Portfolio&gt; _repository;<br><br>    public AddPortfolioHandler(IRepository&lt;Portfolio&gt; repository,<br>        IMultiTenancyService multiTenancyService)<br>    {<br>        _repository = repository;<br>        _multiTenancyService = multiTenancyService;<br>    }<br><br>    public async Task&lt;Result&lt;Guid&gt;&gt; Handle(AddPortfolioCommand request, CancellationToken cancellationToken)<br>    {<br>        try<br>        {<br>            var portfolio = new Portfolio(request.Name, request.CurrencyCode);<br>            portfolio.TenantId = _multiTenancyService.CurrentTenant;<br><br>            await _repository.AddAsync(portfolio, cancellationToken);<br>            return Result.Ok(portfolio.Id);<br>        }<br>        catch (ArgumentException ex)<br>        {<br>            return Result.Fail&lt;Guid&gt;(ex.Message);<br>        }<br>    }<br>}</pre><p>7. Returning to our <strong>Infrastructure</strong> project, we must ensure that the user will be provided only with data associated with her and only her tenancy. To achieve this, we add a global filter in AppDbContext for Portfolio entity into the overridden method OnModelCreating(). Additionally, we specify a new index based on the TenantId field to improve read query performance.</p><pre>public class AppDbContext : IdentityDbContext<br>{<br>    private readonly IMultiTenancyService _multiTenancyService;<br><br>    public AppDbContext(DbContextOptions&lt;AppDbContext&gt; options,<br>        IMultiTenancyService multiTenancyService)<br>        : base(options)<br>    {<br>        _multiTenancyService = multiTenancyService;<br>    }<br><br>    protected override void OnModelCreating(ModelBuilder modelBuilder)<br>    {<br>        base.OnModelCreating(modelBuilder);<br><br>        modelBuilder.Entity&lt;Portfolio&gt;()<br>            .HasQueryFilter(b =&gt; b.TenantId == _multiTenancyService.CurrentTenant)<br>            .HasIndex(b =&gt; b.TenantId)<br>            .IsUnique(false);    <br>    }<br>}</pre><p>8. Next, we switch to the <strong>WebAPI </strong>project, where it’s necessary to read a tenancy claim from <strong>HTTP cookies</strong> and set the TenantId in MultiTenancyService using a specially created MultiTenancy middleware.</p><pre>public class MultiTenancy<br>{<br>    private readonly RequestDelegate _next;<br><br>    public MultiTenancy(RequestDelegate next)<br>    {<br>        _next = next;<br>    }<br><br>    public async Task Invoke(HttpContext httpContext, IMultiTenancyService multiTenancyService)<br>    {<br>        var tenantId = DetermineTenant(httpContext);<br><br>        multiTenancyService.SetCurrentTenant(tenantId);<br><br>        await _next(httpContext);<br>    }<br><br>    private string DetermineTenant(HttpContext context)<br>    {<br>        var user = context.User;<br>        if (user.HasClaim(c =&gt; c.Type == &quot;tenant&quot;))<br>        {<br>            return user.FindFirst(&quot;tenant&quot;)?.Value ?? string.Empty;<br>        }<br><br>        return &quot;default-tenant&quot;;<br>    }<br>}</pre><p>9. Subsequently, we must incorporate our MultiTenancy middleware in the Program.cs file. It should be added after the authentication process, as we will read a TenantId from the authenticated user’s <strong>HttpContext</strong>.</p><pre>app.UseAuthentication();<br>app.UseAuthorization();<br>app.UseMiddleware&lt;Middlewares.MultiTenancy&gt;();<br>app.MapControllers();</pre><p>10. Finally, we must ensure the TenantId is generated and stored as a Claim in the user’s profile during the client registration process in the Authentication controller, and then returned to <strong>HTTP cookies</strong> upon successful authentication.</p><pre>[HttpPost(&quot;Register&quot;)]<br>public async Task&lt;IActionResult&gt; Register([FromBody] UserDto model)<br>{<br>    if (ModelState.IsValid)<br>    {<br>        var user = new IdentityUser { UserName = model.Name, Email = model.Email };<br>        var result = await _userManager.CreateAsync(user, model.Password);<br><br>        if (result.Succeeded)<br>        {<br>            var tenantId = Guid.NewGuid().ToString();<br>            var tenantClaim = new Claim(&quot;tenant&quot;, tenantId);<br>            await _userManager.AddClaimAsync(user, tenantClaim);<br><br>            return Ok(new { message = &quot;User registered successfully&quot; });<br>        }<br><br>        foreach (var error in result.Errors)<br>        {<br>            ModelState.AddModelError(string.Empty, error.Description);<br>        }<br>    }<br><br>    return BadRequest(ModelState);<br>}</pre><h3>Conclusion</h3><p>Implementing multi-tenancy in an <strong>ASP.NET Core WebAPI</strong> is a strategic approach to managing and protecting client data across multiple tenants within a single application instance. We explored the essential steps to set up a multi-tenant architecture using <strong>ASP.NET Core Identity</strong> and <strong>Entity Framework Core</strong>, ensuring data isolation and security while maintaining performance and scalability.</p><p>We’ve demonstrated how multi-tenancy can be achieved through a shared database and shared schema approach, leveraging <strong>ASP.NET Core Identity</strong> for user management and custom <strong>MultiTenancy </strong>middleware for tenant identification. Following the practical example, you can adapt these concepts for your projects, ensuring each client’s data remains secure and isolated, even in a shared environment.</p><p>Multi-tenancy offers numerous benefits, including cost efficiency, ease of maintenance, and scalability, making it an attractive option for <strong>SaaS</strong> applications and services. However, it’s crucial to be mindful of the potential complexities and security implications, planning your implementation carefully to avoid performance issues and ensure robust data protection.</p><p>Whether you’re building a new application or enhancing an existing one, I hope the principles and practices outlined in this guide will help you navigate multi-tenancy challenges, enabling you to deliver a more flexible, secure, and scalable solution to your users.</p><p><strong>Subscribe for more insights and in-depth analysis:</strong></p><ul><li><a href="https://sharpassembly.medium.com/">SharpAssembly on Medium</a></li><li><a href="https://dev.to/sharpassembly">SharpAssembly on Dev.to</a></li><li><a href="https://t.me/SharpAssembly">SharpAssembly on Telegram</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J3GcfzE1WdNrEjXi" /><figcaption>Credits: DALL·E generated</figcaption></figure><p>#DDD #InWestMan</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f11b3bf88c56" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sharpassembly/step-by-step-guide-to-implementing-multi-tenancy-in-webapi-using-asp-net-core-identity-f11b3bf88c56">Step-by-step Guide to Implementing Multi-Tenancy in WebAPI Using ASP.NET Core Identity</a> was originally published in <a href="https://medium.com/sharpassembly">SharpAssembly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring Currency: Mastering Universal Currency Value Objects with Enums and Attributes]]></title>
            <link>https://medium.com/sharpassembly/refactoring-currency-mastering-universal-currency-value-objects-with-enums-and-attributes-171b1ae5681d?source=rss-a27d5e81061b------2</link>
            <guid isPermaLink="false">https://medium.com/p/171b1ae5681d</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kostiantyn Bilous]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 05:26:10 GMT</pubDate>
            <atom:updated>2024-01-31T08:37:13.506Z</atom:updated>
            <content:encoded><![CDATA[<p>Precision is paramount in financial software development, where even seemingly minor components can have major implications. Among these, the representation of <em>Currency </em>stands as a foundational element that demands meticulous attention. This article delves into the art of refining <em>Currency </em>objects within financial systems. By adopting <strong>Domain-Driven Design (DDD)</strong> principles, we’ll explore how to transform <strong><em>Currency </em></strong>from a basic <strong>Entity</strong> into a well-defined <strong>Value Object</strong>. Discover how crafting robust and universal <em>Currency </em><strong>Value Objects</strong> can subtly yet significantly enhance the clarity and reliability of financial applications.</p><h3>Theoretical Underpinnings: Entities and Value Objects in Domain-Driven Design</h3><p>In <strong>Domain-Driven Design (DDD)</strong>, understanding the distinction between <strong>Entities </strong>and <strong>Value Objects</strong> is fundamental. <strong>Entities </strong>are defined by their identity, while<strong> Value Objects</strong> are characterized by their attributes. Often misconstrued as a mere attribute, <em>Currency </em>holds substantial complexity, primarily when interacting with different system parts. It could be misconceptually implemented as an <strong>Entity </strong>in the <strong>Bounded Context,</strong> where it naturally behaves as a <strong>Value Object</strong>.</p><p><a href="https://sharpassembly.medium.com/entity-value-object-and-aggregate-root-in-domain-driven-design-0ce9402e4ad3">Entity, Value Object, and Aggregate Root in Domain-Driven Design</a></p><h4>Why Refactor <em>Currency</em> into a Value Object?</h4><ul><li><strong>Immutability: Value Objects</strong> are immutable. This immutability aligns perfectly with the nature of the <em>Currency</em>, where the value shouldn’t change once instantiated.</li><li><strong>Validation and Consistency:</strong> Encapsulating the currency as a <strong>Value Object </strong>allows centralized validation and business rule enforcement, ensuring <em>Currency </em>consistency<strong><em> </em></strong>across the system.</li><li><strong>Reduction of Complexity:</strong> Representing <em>Currency </em>as a <strong>Value Object</strong> simplifies operations, abstracting the intricacies of currency handling into well-defined methods.</li></ul><h3>Practical Application: The Refactoring Process</h3><p>Let’s dive into the practicalities using an example from the <strong><em>InWestMan</em></strong> application. This application is designed for personal investment tracking and uses <em>Money</em> as a <strong>Value Object</strong>.</p><h4>Original Scenario: Currency as an Entity</h4><p>Initially, the <em>Currency </em>in our system was an <strong>Entity</strong> laden with unnecessary complexity and potential for inconsistencies.</p><pre>public class Currency : BaseEntity&lt;int&gt; <br>{<br>    public string Code { get; set; }<br>    public string Name { get; set; }<br>    public int FractionDigits { get; set; }<br>}</pre><p>This Currency class is a part of the Money class, an <strong>Enterprise Pattern</strong> commonly used in <strong>Domain-Driven Design</strong>.</p><p><a href="https://sharpassembly.medium.com/money-patterns-in-domain-driven-design-navigating-the-complexities-of-financial-systems-5f45cfcfec08">Money Patterns in Domain-Driven Design: Navigating the Complexities of Financial Systems</a></p><pre>public sealed class Money : ValueObject<br>{<br>    private readonly decimal _amount;<br><br>    public Money(decimal amount, Currency currency)<br>    {<br>        _amount = amount;<br>        Currency = currency;<br>    }<br><br>    public Currency Currency { get; }<br><br>    public decimal Amount =&gt; decimal.Round(_amount, Currency.FractionDigits, MidpointRounding.ToEven);<br>    <br>    protected override IEnumerable&lt;object&gt; GetEqualityComponents()<br>    {<br>        yield return Amount;<br>        yield return CurrencyCode;<br>    }<br><br>    // Methods<br>}</pre><p>Now, let’s define our refactoring strategy.</p><h4>Refactoring Steps</h4><p><strong>1 Defining the Immutable Enum: </strong>We define a new CurrencyCode enum (e.g., <a href="https://en.wikipedia.org/wiki/ISO_4217">ISO 4217</a>), encapsulating all relevant properties and behaviors in its attributes.</p><pre>public enum CurrencyCode<br>{<br>    [EnumMember(Value = &quot;USD&quot;)] <br>    [Description(&quot;United States dollar&quot;)] <br>    [FractionDigit(2)]<br>    USD = 840,<br><br>    [EnumMember(Value = &quot;UAH&quot;)] <br>    [Description(&quot;Ukrainian hryvnia&quot;)] <br>    [FractionDigit(2)]<br>    UAH = 980,<br><br>    [EnumMember(Value = &quot;EUR&quot;)] <br>    [Description(&quot;Euro&quot;)] <br>    [FractionDigit(2)]<br>    EUR = 978<br><br>    ...<br>}</pre><p><strong>2 Store data in memory as Attributes: </strong>We ensure that instances of CurrencyCode contain all relevant data.</p><pre>[AttributeUsage(AttributeTargets.Field)]<br>public class FractionDigitAttribute : Attribute<br>{<br>    public FractionDigitAttribute(int fractionDigit)<br>    {<br>        FractionDigit = fractionDigit;<br>    }<br><br>    public int FractionDigit { get; private set; }<br>}</pre><p><strong>3 Centralizing Business Logic:</strong> Currency-related data (like full name, fraction digits, etc.) are centralized within the CurrencyCode enum, promoting code reusability and maintainability by static extensions.</p><pre>public static class CurrencyCodeExtensions<br>{<br>    public static int GetFractionDigit(this CurrencyCode currencyCode)<br>    {<br>        var type = currencyCode.GetType();<br>        var memInfo = type.GetMember(currencyCode.ToString());<br>        if (memInfo.Length &gt; 0)<br>        {<br>            var attributes = memInfo[0].GetCustomAttributes(typeof(FractionDigitAttribute), false);<br>            if (attributes.Length &gt; 0)<br>                return ((FractionDigitAttribute)attributes[0]).FractionDigit;<br>        }<br><br>        return 2;<br>    }<br>}</pre><p>In the context of our Money class, the refactoring leads to more transparent, more concise operations:</p><pre>public sealed class Money : ValueObject<br>{<br>    private readonly decimal _amount;<br>    private readonly int _fractionDigits;<br><br>    public Money(decimal amount, CurrencyCode currencyCode)<br>    {<br>        _amount = amount;<br>        CurrencyCode = currencyCode;<br>        _fractionDigits = CurrencyCode.GetFractionDigit();<br>    }<br><br>    public decimal Amount =&gt; decimal.Round(_amount, _fractionDigits, MidpointRounding.ToEven);<br><br>    public CurrencyCode CurrencyCode { get; }<br><br>    protected override IEnumerable&lt;object&gt; GetEqualityComponents()<br>    {<br>        yield return Amount;<br>        yield return CurrencyCode;<br>    }<br><br>    // Other methods <br>}</pre><p>The Money class, now interacting with CurrencyCode as a universal <strong>Value Object </strong>and<strong> </strong>represents the financial domain more expressively.</p><h3>Conclusion: The Strategic Impact of Refactoring</h3><p>The transition from treating <em>Currency </em>as an <strong>Entity </strong>to a <strong>Value Object</strong> in financial software isn’t merely a technical refactor but a strategic enhancement. It aligns the codebase with the principles of <strong>Domain-Driven Design</strong>, promoting clarity, consistency, and maintainability. This refactoring journey exemplifies how thoughtful changes in code structure can lead to more robust, reliable, and scalable financial systems.</p><p><strong>Subscribe for more insights and in-depth analysis:</strong></p><ul><li><a href="https://sharpassembly.medium.com/">SharpAssembly on Medium</a></li><li><a href="https://dev.to/sharpassembly">SharpAssembly on Dev.to</a></li><li><a href="https://t.me/SharpAssembly">SharpAssembly on Telegram</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-uLXXyRo9xgtv244XcgjWw.png" /><figcaption>Credits: DALL·E generated</figcaption></figure><p>#DDD #InWestMan</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=171b1ae5681d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sharpassembly/refactoring-currency-mastering-universal-currency-value-objects-with-enums-and-attributes-171b1ae5681d">Refactoring Currency: Mastering Universal Currency Value Objects with Enums and Attributes</a> was originally published in <a href="https://medium.com/sharpassembly">SharpAssembly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Money Patterns in Domain-Driven Design: Navigating the Complexities of Financial Systems]]></title>
            <link>https://medium.com/sharpassembly/money-patterns-in-domain-driven-design-navigating-the-complexities-of-financial-systems-5f45cfcfec08?source=rss-a27d5e81061b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f45cfcfec08</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-design]]></category>
            <dc:creator><![CDATA[Kostiantyn Bilous]]></dc:creator>
            <pubDate>Tue, 16 Jan 2024 05:54:06 GMT</pubDate>
            <atom:updated>2024-01-16T05:54:06.769Z</atom:updated>
            <content:encoded><![CDATA[<p>The world of finance seems simple at first glance: numbers on a screen, transfers, balances. However, behind these seemingly obvious operations lies a deep complexity. Every keystroke in a banking application, every transaction, results from complex processes without room for error. In this context, <strong>domain-driven design (DDD) </strong>is a crucial approach that transforms complex financial tasks into clearly structured solutions.</p><p>This article reveals how <strong>Money </strong>patterns within <strong>DDD</strong> help decipher these complexities and provide effective methods for managing and processing financial resources in software systems, emphasizing their crucial role in creating reliable financial applications.</p><h3>Theoretical Underpinnings: Why Money Matters in DDD</h3><p><strong>Domain-driven design</strong> is all about modeling software to match the domain it’s intended to serve. <strong><em>Money </em></strong>is a fundamental concept in financial systems, but it’s often mistakenly simplified as a mere number. This oversimplification can lead to critical issues like rounding errors and currency mismatches, which are unacceptable in precision-critical financial applications.</p><h4>Key Concepts:</h4><ul><li><strong>Immutability</strong>: In <strong>DDD</strong>, <strong><em>Money </em></strong>is typically modeled as a <strong>Value Object</strong>, which means it’s immutable and defined by its attributes (like amount and currency) rather than an identity.</li></ul><p><a href="https://sharpassembly.medium.com/entity-value-object-and-aggregate-root-in-domain-driven-design-0ce9402e4ad3">Entity, Value Object, and Aggregate Root in Domain-Driven Design</a></p><ul><li><strong>Precision and Scale</strong>: Financial calculations demand high precision, and <strong><em>Money </em></strong>patterns address this by using appropriate data types, such as decimal to avoid rounding errors.</li><li><strong>Currency Operations</strong>: Different currencies and their conversions are a core part of financial applications, necessitating a robust handling mechanism in the domain model.</li></ul><h3>Practical Application: Implementing Money in the Investment Domain</h3><p>Let’s dive into a practical scenario in the investment domain. Consider an example from the <em>InWestMan </em>application, designed for personal investment tracking, which helps individual investors manage their portfolios. In such a system, accurately representing and manipulating monetary values is crucial.</p><h4>Example: Portfolio Valuation</h4><p>Imagine a feature that calculates the total value of an investor’s portfolio. This involves summing up the values of various assets, potentially in different currencies.</p><pre>public sealed class Money<br>{<br>    public decimal Amount { get; }<br>    public Currency Currency { get; }<br><br>    public Money(decimal amount, Currency currency)<br>    {<br>        Amount = amount;<br>        Currency = currency;<br>    }<br><br>    public Money Add(Money other)<br>    {<br>        CheckSameCurrency(other)<br>        return new Money(this.Amount + other.Amount, this.Currency);<br>    }<br><br>    private void CheckSameCurrency(Money other) <br>    {<br>        if (Currency != other.Currency) <br>              throw new CurrencyMismatchException();<br>    }<br><br>    public static Money operator +(Money a, Money b) <br>    {<br>        return a.Add(b);<br>    }<br><br>    // More methods like Subtract, Multiply, etc.<br>}<br><br>public class Portfolio<br>{<br>    private List&lt;Investment&gt; Investments;<br><br>    public Money CalculateTotalValue()<br>    {<br>        Money totalValue = new Money(0, Currency.USD); // Assuming USD for simplicity<br>        foreach (var investment in Investments)<br>        {<br>            totalValue = totalValue + investment.CurrentValue;<br>        }<br>        return totalValue;<br>    }<br>}</pre><p>In this snippet Money is a <strong>Value Object</strong> with operations that ensure safe financial calculations. The Portfolio class uses Money to calculate the total value, ensure that domain rules like currency consistency are followed.</p><h3>Conclusion: The Strategic Advantage of Money Patterns in DDD</h3><p>Integrating <strong><em>Money Patterns</em></strong> in <strong>DDD </strong>provides a comprehensive technical solution through a strategic approach to creating reliable, accurate, and domain-oriented financial software. Considering the complexity and significance of money allows for developing scalable, reliable, and, most importantly, trustworthy systems. Thus, the application of <strong><em>Money Patterns</em></strong> in financial programs ensures the accuracy of financial calculations.</p><p><strong>Subscribe for more insights and in-depth analysis:</strong></p><ul><li><a href="https://sharpassembly.medium.com/">SharpAssembly on Medium</a></li><li><a href="https://t.me/SharpAssembly">SharpAssembly on Telegram</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FSwVFvegp4oxgA60" /><figcaption>Credits: DALL·E generated</figcaption></figure><p><em>#DDD #InWestMan</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f45cfcfec08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sharpassembly/money-patterns-in-domain-driven-design-navigating-the-complexities-of-financial-systems-5f45cfcfec08">Money Patterns in Domain-Driven Design: Navigating the Complexities of Financial Systems</a> was originally published in <a href="https://medium.com/sharpassembly">SharpAssembly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elevating Solution Design with the TDD/BDD Approach: A Code Example]]></title>
            <link>https://medium.com/sharpassembly/elevating-solution-design-with-the-tdd-bdd-approach-a-code-example-2e7afa5bca97?source=rss-a27d5e81061b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e7afa5bca97</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Kostiantyn Bilous]]></dc:creator>
            <pubDate>Sat, 30 Dec 2023 07:43:20 GMT</pubDate>
            <atom:updated>2024-01-13T05:41:18.731Z</atom:updated>
            <content:encoded><![CDATA[<p>In the dynamic world of software development, solutions&#39; integrity, accuracy, and reliability are paramount. Embracing these qualities, <strong>Test-Driven Development (TDD)</strong>, a modern software engineering methodology introduced by <a href="https://medium.com/@kentbeck_7670">Kent Beck</a>, emerges as a vital strategy for navigating complex domain challenges. This article delves into the practical application of <strong>TDD</strong>, illustrating its profound influence on the design of software solutions.</p><p>Our exploration begins with a focus on <a href="https://specflow.org/"><strong>SpecFlow</strong></a>, an adaptation of the <a href="https://cucumber.io/"><strong>Cucumber</strong> language</a> for <strong>.NET</strong>. <strong>SpecFlow</strong> stands at the intersection of technical and non-technical domains, employing a simple, domain-specific language that demystifies software behavior for all stakeholders. This tool, rooted in <strong>Behavior-Driven Development (BDD)</strong>, is pivotal in translating complex software concepts into accessible terms.</p><p>We venture into a case study using <strong>SpecFlow </strong>to implement trade transaction booking and update investment portfolios via a WebAPI. This scenario will serve as a practical backdrop to demonstrate how <strong>TDD </strong>enriches solution design and underpins the rationale for employing <a href="https://sharpassembly.medium.com/entity-value-object-and-aggregate-root-in-domain-driven-design-0ce9402e4ad3"><strong>Domain-Driven Development</strong> (<strong>DDD)</strong></a> and <a href="https://sharpassembly.medium.com/cqrs-repository-and-mediatr-65883d1a1fac"><strong>Command and Query Responsibility Segregation</strong> (<strong>CQRS)</strong></a> architecture patterns. Our journey through this case study aims to build a feature that meets technical and business requirements and emphasizes maintainability, scalability, and clarity.</p><ul><li><a href="https://sharpassembly.medium.com/entity-value-object-and-aggregate-root-in-domain-driven-design-0ce9402e4ad3">Entity, Value Object, and Aggregate Root in Domain-Driven Design</a></li><li><a href="https://sharpassembly.medium.com/cqrs-repository-and-mediatr-65883d1a1fac">CQRS, Repository, and MediatR</a></li></ul><p>Central to our discussion is the objective of situating business logic firmly within the Domain Layer, ensuring minimal complexity in the layers above. By the end of this article, you will have a comprehensive understanding of how <strong>TDD</strong> and <strong>BDD</strong> can be effectively applied to enhance software development processes.</p><p>Now, let&#39;s dive into our example, beginning with a <strong>SpecFlow</strong> scenario for bond purchasing and subsequent portfolio position updating.</p><h4>Example (Add Trade Transaction and Update Portfolio positions)</h4><p>Let&#39;s define a <strong>SpecFlow </strong>scenario for bond purchasing and subsequent updates to portfolio positions. For this scenario, we&#39;ll assume that all steps except <em>&quot;</em><strong><em>WHEN</em></strong><em> a user adds transactions&quot;</em> have already been implemented.</p><pre>Scenario: User can add a new position to a portfolio<br> GIVEN bond with name &quot;BOND 1&quot; is created<br>   AND bank account with name &quot;BANK ACCOUNT 1&quot; is created<br>  WHEN a user adds transactions<br>   | TradeDate  | TradeType | BondName | Amount | Price | BankAccountName |<br>   | 2023–01–01 | Buy       | BOND 1   | 20     | 1000  | BANK ACCOUNT 1  |<br>  THEN the positions in the portfolio on &quot;2023–01–01&quot; are:<br>   | AssetName      | CustodyName | Balance | CostBasisAmount |<br>   | BOND 1         | CUST1       | 20      | 20000           |<br>   | BANK ACCOUNT 1 | CUST1       | -20000  | 0               |</pre><p>So, after defining the <strong>SpecFlow </strong>scenario, we need to implement the <em>&quot;</em><strong><em>WHEN</em></strong><em> a user adds transactions&quot;</em> step in our <strong><em>PortfolioControllerStepDefinitions</em></strong><em> </em>class.</p><pre>public class PortfolioControllerStepDefinitions : IClassFixture&lt;CustomWebApplicationFactory&lt;Program&gt;&gt; <br>{<br>    public PortfolioControllerStepDefinitions(CustomWebApplicationFactory&lt;Program&gt; factory) {<br>        _factory = factory;<br>    }<br><br>    //...<br><br>    [When(@&quot;user adds transactions&quot;)]<br>    public async Task WhenUserAddsTransactions(Table table) {<br>        var tradeBondTransactionDto = table.CreateSet&lt;TradeBondTransactionDto&gt;();<br>        using var client = _factory.CreateClient();<br><br>        foreach (var transaction in tradeBondTransactionDto) {<br>            var createDto = new CreateTradeBondTransactionDto {<br>                BondId = _bond.Id,<br>                BondPortfolioId = _bondPortfolio.Id,<br>                BondCustodyId = _bondCustody.Id,<br>                BankAccountId = _bankAccount.Id,<br>                BankAccountPortfolioId = _bankAccountPortfolio.Id,<br>                BankAccountCustodyId = _bankAccountCustody.Id,<br>                Amount = transaction.Amount,<br>                Price = transaction.Price,<br>                TradeDate = transaction.TradeDate,<br>                TradeType = transaction.TradeType<br>            };<br><br>            var content = ControllerTestHelper.SerializeToJsonStringContent(createDto);<br><br>            var response = await client.PostAsync(&quot;/Bond/Trade&quot;, content);<br>            response.EnsureSuccessStatusCode();<br>        }<br>    }    <br>    <br>    //...<br>}</pre><p>When we run the test, it initially fails, indicating the absence of a POST &quot;<strong><em>/Bond/Trade&quot;</em></strong> route in our system. This failure is intentional in <strong>TDD</strong>, as it guides us in implementing the necessary production code to pass the test. Thus, we start by extending the BondController with a Trade method, incorporating the <strong>MediatR</strong> library to execute <strong>Domain Commands</strong>, a <a href="https://sharpassembly.medium.com/cqrs-repository-and-mediatr-65883d1a1fac">technique that reinforces our commitment to maintaining a <strong>CQRS</strong> architecture.</a></p><p><a href="https://sharpassembly.medium.com/cqrs-repository-and-mediatr-65883d1a1fac">CQRS, Repository, and MediatR</a></p><pre>[ApiController]<br>[Route(&quot;[controller]&quot;)]<br>public class BondController : Controller<br>{    <br>    //...<br><br>    [HttpPost(&quot;Trade&quot;)]<br>    public async Task&lt;IActionResult&gt; Trade(CreateTradeBondTransactionDto createDto)<br>    {<br>        var command = _mapper.Map&lt;AddTradeBondTransactionCommand&gt;(createDto);<br>        var result = await _mediator.Send(command);<br>        if (result.IsFailed) return BadRequest(result.Errors);<br>        var transaction = await _transactionRepository.GetByIdAsync(result.Value);<br>        var transactionDto = _mapper.Map&lt;TransactionDto&gt;(transaction);<br>        return CreatedAtAction(nameof(Trade), transactionDto);<br>    }<br>    //...<br>}</pre><p>To align with our WebAPI structure, we then introduce a <strong>Data Transfer Object (DTO)</strong>, CreateTradeBondTransactionDto, which acts as a data contract for our new POST request <strong><em>&quot;/Bond/Trade&quot;</em></strong>:</p><pre>public class CreateTradeBondTransactionDto<br>{<br>    public DateTime TradeDate { get; set; }<br>    public TradeType TradeType { get; set; }<br>    public decimal Price { get; set; }<br>    public decimal Amount { get; set; }<br><br>    public Guid BankAccountId { get; set; }<br>    public Guid BankAccountCustodyId { get; set; }<br>    public Guid BankAccountPortfolioId { get; set; }<br><br>    public Guid BondId { get; set; }<br>    public Guid BondCustodyId { get; set; }<br>    public Guid BondPortfolioId { get; set; }<br>}</pre><p>Next, we focus on the Domain Layer, creating the AddTradeBondTransactionCommand. This command bridges our WebAPI model <strong>DTO </strong>and the internal <strong>Domain Comand </strong>contract facilitated by <strong>AutoMapper</strong>.</p><pre>public class AddTradeBondTransactionCommand : IRequest&lt;Result&lt;Guid&gt;&gt;<br>{<br>    public DateTime TradeDate { get; set; }<br>    public TradeType TradeType { get; set; }<br>    public decimal Price { get; set; }<br>    public decimal Amount { get; set; }<br><br>    public Guid BankAccountId { get; set; }<br>    public Guid BankAccountCustodyId { get; set; }<br>    public Guid BankAccountPortfolioId { get; set; }<br><br>    public Guid BondId { get; set; }<br>    public Guid BondCustodyId { get; set; }<br>    public Guid BondPortfolioId { get; set; }<br>}</pre><p>After defining our <strong>Controller</strong> method and <strong>DTO</strong>, we address the implementation of the <strong>Command Handler</strong>, AddTradeBondTransactionHandler, in the Application Layer. Here, we use a domain TransactionFactory to create a new Transaction object from the <strong>Domain Command</strong>.</p><pre>public class AddTradeBondTransactionHandler : IRequestHandler&lt;AddTradeBondTransactionCommand, Result&lt;Guid&gt;&gt;<br>{<br>    private readonly ILogger&lt;AddTradeBondTransactionCommand&gt; _logger;<br>    private readonly IRepository&lt;Transaction&gt; _transactionRepository;<br><br>    public AddTradeBondTransactionHandler(ILogger&lt;AddTradeBondTransactionCommand&gt; logger,<br>        IRepository&lt;Transaction&gt; transactionRepository)<br>    {<br>        _logger = logger;<br>        _transactionRepository = transactionRepository;<br>    }<br><br>    public async Task&lt;Result&lt;Guid&gt;&gt; Handle(AddTradeBondTransactionCommand request, CancellationToken cancellationToken)<br>    {<br>        _logger.LogInformation($&quot;Adding buy bond transaction in InWestMan database on: {request.TradeDate}&quot;);<br><br>        try<br>        {<br>            var transaction = TransactionFactory.CreateTradeTransaction(request);<br>            var transactionAdded = await _transactionRepository.AddAsync(transaction, cancellationToken);<br>            await _transactionRepository.SaveChangesAsync(cancellationToken);<br>            _logger.LogInformation(<br>                $&quot;Buy bond transaction is added in InWestMan database. Transaction id: {transactionAdded.Id}&quot;);<br><br>            return Result.Ok(transactionAdded.Id);<br>        }<br>        catch (Exception ex)<br>        {<br>            _logger.LogError(ex, &quot;Error processing buy bond transaction&quot;);<br>            return Result.Fail&lt;Guid&gt;(ex.Message);<br>        }<br>    }<br>}</pre><pre>public static class TransactionFactory<br>{   <br>    public static Transaction CreateTradeTransaction(AddTradeBondTransactionCommand request)<br>    {<br>        Transaction transaction;<br>        switch (request.TradeType)<br>        {<br>            case TradeType.Buy:<br>                transaction = new BuyBondTransaction(request.TradeDate,<br>                    request.BankAccountId,<br>                    request.BankAccountCustodyId,<br>                    request.BankAccountPortfolioId,<br>                    request.Price * request.Amount * -1,<br>                    request.BondId,<br>                    request.BondCustodyId,<br>                    request.BondPortfolioId,<br>                    request.Amount);<br>                break;<br>            case TradeType.Sell:<br>                transaction = new SellBondTransaction(request.TradeDate,<br>                    request.BondId,<br>                    request.BondCustodyId,<br>                    request.BondPortfolioId,<br>                    request.Amount * -1,<br>                    request.BankAccountId,<br>                    request.BankAccountCustodyId,<br>                    request.BankAccountPortfolioId,<br>                    request.Price * request.Amount);<br>                break;<br>            default:<br>                throw new ArgumentOutOfRangeException();<br>        }<br><br>        transaction.MarkAsCreated();<br>        return transaction;<br>    }<br>}</pre><p>With the new Transaction added to our database, we must inform our system to recalculate portfolio positions. This is achieved by marking our Transaction as created and generating a corresponding <strong>Domain Event</strong>, EntityCreated&lt;Transaction&gt;. This event should be handled when the Transaction is saved to the database.</p><p>To make it work, let&#39;s delve into the Transaction<strong><em> </em></strong>domain, where we add a MarkAsCreated<em> </em>method to add an EntityCreated&lt;Transaction&gt;<strong> Domain Event</strong> to the Events collection.</p><pre>public class BuyBondTransaction : Transaction<br>{<br>    public BuyBondTransaction(DateTime paymentDate, Guid assetFromId, Guid custodyFromId, Guid portfolioFromId,<br>        decimal amountFrom,<br>        Guid assetToId, Guid custodyToId, Guid portfolioToId, decimal amountTo)<br>    {<br>        Type = TransactionType.BuyBond;<br>        PaymentDate = Guard.Against.Null(paymentDate, nameof(PaymentDate));<br>        if (amountFrom &gt; 0) throw new ArgumentException(&quot;Bank Account payment must be negative&quot;);<br>        if (amountTo &lt; 0) throw new ArgumentException(&quot;Buy Bond amount must be positive&quot;);<br>        var legShort = new Leg(assetFromId, custodyFromId, portfolioFromId, amountFrom);<br>        var legLong = new Leg(assetToId, custodyToId, portfolioToId, amountTo);<br>        Legs.Add(legShort);<br>        Legs.Add(legLong);<br>    }<br>}<br><br>public class SellBondTransaction : Transaction<br>{<br>    public SellBondTransaction(DateTime paymentDate, Guid assetFromId, Guid custodyFromId, Guid portfolioFromId,<br>        decimal amountFrom,<br>        Guid assetToId, Guid custodyToId, Guid portfolioToId, decimal amountTo)<br>    {<br>        Type = TransactionType.SellBond;<br>        PaymentDate = Guard.Against.Null(paymentDate, nameof(PaymentDate));<br>        if (amountFrom &gt; 0) throw new ArgumentException(&quot;Sell Bond amount must be negative&quot;);<br>        if (amountTo &lt; 0) throw new ArgumentException(&quot;Bank Account payment must be positive&quot;);<br>        var legShort = new Leg(assetFromId, custodyFromId, portfolioFromId, amountFrom);<br>        var legLong = new Leg(assetToId, custodyToId, portfolioToId, amountTo);<br>        Legs.Add(legShort);<br>        Legs.Add(legLong);<br>    }<br>}<br><br>public abstract class Transaction : BaseEntity&lt;Guid&gt;, IAggregateRoot<br>{<br>    public DateTime PaymentDate { get; set; }<br>    public TransactionType Type { get; set; }<br>    public ICollection&lt;Leg&gt; Legs { get; set; }<br><br>    public void MarkAsCreated() {<br>        Events.Add(new EntityCreated&lt;Transaction&gt;(this));<br>    }<br>}<br><br>public abstract class BaseEntity&lt;TId&gt;<br>{<br>    public List&lt;BaseDomainEvent&gt; Events = new();<br>    public TId Id { get; set; }<br>}</pre><p>After that, we introduce the generic <strong>Domain Event,</strong> EntityCreated&lt;T&gt;, for any <strong>Entity </strong>by implementing <strong>MediatR&#39;s </strong>INotification<em> </em>interface.</p><pre>public class EntityCreated&lt;T&gt; : BaseDomainEvent where T : class, IAggregateRoot<br>{<br>    public T Entity;<br>    public EntityCreated(T entity)<br>    {<br>        Entity = entity;<br>    }<br><br>}<br><br>public abstract class BaseDomainEvent : INotification { <br>}</pre><p>Finally, we turn to the Infrastructure Layer. Here, we override SaveChangesAsync in AppDbContext, using the <strong>MediatR</strong> library to invoke all registered <strong>Domain Events</strong> upon saving to the database.</p><blockquote>This approach was inspired by <a href="https://github.com/ardalis/pluralsight-ddd-fundamentals/blob/main/ClinicManagement/src/ClinicManagement.Infrastructure/Data/AppDbContext.cs">Ardalis’s DDD course</a>.</blockquote><pre>public class AppDbContext : DbContext<br>{<br>    private readonly IMediator _mediator;<br><br>    public AppDbContext(DbContextOptions&lt;AppDbContext&gt; options, IMediator mediator)<br>        : base(options)<br>    {<br>        _mediator = mediator;<br>    }    <br><br>  //...<br><br>    public override async Task&lt;int&gt; SaveChangesAsync(CancellationToken cancellationToken = new()) {<br>        var entitiesWithPreSaveEvents = ChangeTracker<br>            .Entries&lt;BaseEntity&lt;Guid&gt;&gt;()<br>            .Where(e =&gt; e.Entity.Events != null &amp;&amp; e.Entity.Events.Any())<br>            .Select(e =&gt; new { Entity = e.Entity, Events = e.Entity.Events.ToArray() })<br>            .ToList();<br>        <br>        var result = await base.SaveChangesAsync(cancellationToken).ConfigureAwait(false);<br>        <br>        if (_mediator == null) return result;<br>        foreach (var entityWithEvents in entitiesWithPreSaveEvents) {<br>            entityWithEvents.Entity.Events.Clear();<br>            foreach (var domainEvent in entityWithEvents.Events) {<br>                await _mediator.Publish(domainEvent, cancellationToken).ConfigureAwait(false);<br>            }<br>        }<br>        return result;<br>    }<br><br>   //...<br>}</pre><p>To complete the process, we implement the TransactionAddedHandler, which updates portfolio positions using the UpdatePositionsOnAdd method within the Portfolio entity. This handler also demonstrates the application of <a href="https://sharpassembly.medium.com/choosing-a-data-reading-architecture-in-net-four-approaches-12256b1fd606">the <strong>Specification</strong> pattern, a topic we&#39;ve explored in previous discussions</a>.</p><p><a href="https://sharpassembly.medium.com/choosing-a-data-reading-architecture-in-net-four-approaches-12256b1fd606">Choosing a Data Reading Architecture in .NET: Four Approaches</a></p><pre><br>public class TransactionAddedHandler : INotificationHandler&lt;EntityCreated&lt;Transaction&gt;&gt;<br>{<br>    private readonly ILogger&lt;EntityCreated&lt;Transaction&gt;&gt; _logger;<br>    private readonly IRepository&lt;Portfolio&gt; _portfolioRepository;<br><br>    public TransactionAddedHandler(ILogger&lt;EntityCreated&lt;Transaction&gt;&gt; logger, IRepository&lt;Portfolio&gt; portfolioRepository)<br>    {<br>        _updatedPortfolioIds = new HashSet&lt;Guid&gt;();<br>        _logger = logger;<br>        _portfolioRepository = portfolioRepository;<br>    }<br><br>    private HashSet&lt;Guid&gt; _updatedPortfolioIds { get; }<br><br>    public async Task Handle(EntityCreated&lt;Transaction&gt; notification, CancellationToken cancellationToken)<br>    {<br>        _logger.LogInformation($&quot;Updating portfolios positions for transaction {notification.Entity.Id}&quot;);<br><br>        foreach (var transactionLeg in notification.Entity.Legs)<br>        {<br>            var portfolioSpec = new SinglePortfolioByIdIncludingDependenciesSpecification(transactionLeg.PortfolioId);<br>            var portfolio = await _portfolioRepository.SingleOrDefaultAsync(portfolioSpec, cancellationToken);<br>            if (portfolio == null) throw new ArgumentException($&quot;Portfolio with id {portfolio.Id} not found&quot;);<br><br>            if (_updatedPortfolioIds.Contains(portfolio.Id)) continue;<br><br>            _logger.LogInformation($&quot;Updating portfolio&#39;s {portfolio.Name} positions&quot;);<br>            <br>            portfolio.UpdatePositionsOnAdd(notification.Entity); // core logic of recalculation inside of the portfolio aggregate<br>            <br>            await _portfolioRepository.SaveChangesAsync(cancellationToken);<br>            _updatedPortfolioIds.Add(portfolio.Id);<br>           _logger.LogInformation($&quot;Portfolio&#39;s {portfolio.Name} positions are updated&quot;);<br>        }<br>    }<br>}</pre><p>With these implementations in place, our initial <strong>SpecFlow</strong> test moves from <strong>FAIL</strong> to <strong>PASS</strong>. This successful transition marks the readiness for the next feature development phase, starting with defining new <strong>SpecFlow</strong> scenarios.</p><h4><strong>Conclusion</strong></h4><p>In the realm of modern software engineering, <strong>Test-Driven Development (TDD)</strong> transcends the boundaries of mere testing to embody a holistic design philosophy. Our journey in this article, starting from behavior definition via <strong>SpecFlow </strong>and progressing through a rigorous test-driven process, exemplifies how <strong>TDD</strong> cultivates functional, robust, and maintainable software aligned with precise requirements.</p><p>This methodology underscores the significance of <strong>TDD</strong> in reducing risks, elevating quality, and fostering a profound comprehension of the system. <strong>TDD</strong> champions the clean, maintainable code ethos, primed for adaptability in the face of change. Moreover, the integration of <strong>Behavior-Driven Development (BDD)</strong> complements this approach by bridging the gap between technical and non-technical stakeholders, ensuring that software behavior is comprehensible and relevant to all parties involved.</p><p>Our <strong>TDD/BDD</strong> approach has confirmed the correctness of our solution, which was crafted meticulously using <strong>Domain-Driven Development (DDD)</strong> and <strong>Command and Query Responsibility Segregation (CQRS) </strong>paradigms. We embarked on a top-to-bottom journey, commencing with <strong>SpecFlow </strong>tests, moving through Binding Steps, and then venturing into production code. This progression encompassed the definition of our <strong>Controller </strong>method, <strong>Data Transfer Objects (DTOs)</strong>, <strong>Commands</strong>, <strong>Handlers</strong>, <strong>Entity Factories</strong>, <strong>Entities</strong>, <strong>Domain Events</strong>, and <strong>Domain Event Handlers</strong>, culminating in refining our data Infrastructure Layer.</p><p>This article illustrates the practical application of <strong>TDD/BDD</strong> and serves as a testament to its transformative impact on software solution design. For those seeking to delve deeper into the nuances of <strong>TDD</strong>, <strong>BDD</strong>, <strong>DDD</strong>, and <strong>CQRS</strong> and to understand their synergistic potential in software development, stay tuned for more insights and discussions.</p><p><strong>Subscribe for more insights and in-depth analysis:</strong></p><ul><li><a href="https://sharpassembly.medium.com/">SharpAssembly on Medium</a></li><li><a href="https://t.me/SharpAssembly">SharpAssembly on Telegram</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9xZxEXr23dd5beIR4zOekQ.jpeg" /><figcaption>Credits: DALL·E generated</figcaption></figure><p>#TDD #BDD #DDD #CQRS #InWestMan</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e7afa5bca97" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sharpassembly/elevating-solution-design-with-the-tdd-bdd-approach-a-code-example-2e7afa5bca97">Elevating Solution Design with the TDD/BDD Approach: A Code Example</a> was originally published in <a href="https://medium.com/sharpassembly">SharpAssembly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing a Data Reading Architecture in .NET: Four Approaches]]></title>
            <link>https://medium.com/sharpassembly/choosing-a-data-reading-architecture-in-net-four-approaches-12256b1fd606?source=rss-a27d5e81061b------2</link>
            <guid isPermaLink="false">https://medium.com/p/12256b1fd606</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Kostiantyn Bilous]]></dc:creator>
            <pubDate>Sat, 16 Dec 2023 03:27:11 GMT</pubDate>
            <atom:updated>2023-12-18T15:05:10.575Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine a situation where you are working on an extensive financial application that processes thousands of transactions per minute. You discover that the system&#39;s performance has sharply declined at some point, and users begin to complain about delays. Upon analysis, you find that the cause is an inefficient data reading mechanism that can&#39;t cope with the current volume of information. This example highlights the importance of choosing the right data reading architecture in .NET that affects performance, scalability, and ease of application support. In this article, we will consider four main approaches, allowing each developer to make their own choice, corresponding to the specifics of their project.</p><p>Let&#39;s look at the approaches to reading data in .NET, starting with <strong><em>IQueryable&lt;T&gt;</em></strong>.</p><h3><strong><em>IQueryable&lt;T&gt;</em>: Deferred Execution and Query Flexibility</strong></h3><p>This approach allows repository methods to return an <em>IQueryable&lt;T&gt;</em> collection, deferring the execution of the query until it is used. It enables the dynamic creation of complex queries but can cause performance issues and break encapsulation.</p><h4><strong>Advantages:</strong></h4><ul><li><strong>Deferred execution:</strong> Queries are formed and optimized at the creation stage but only executed when needed.</li><li><strong>Query flexibility: </strong>Allows dynamic creation of complex queries based on existing ones.</li><li><strong>Efficient resource usage: </strong>Using <em>IQueryable&lt;T&gt;</em>, database queries are optimized to retrieve only necessary data. This reduces network and memory load as it avoids fetching unnecessary data.</li><li><strong>Better integration with LINQ:</strong> <em>IQueryable&lt;T&gt;</em> allows integration with <em>LINQ</em> <em>(Language Integrated Query)</em>, providing a robust and convenient syntax for forming queries. This simplifies writing complex queries and improves code readability.</li></ul><h4><strong>Disadvantages:</strong></h4><ul><li><strong>Complexity: </strong>Complex queries can reduce performance, especially with multiple joins and aggregations.</li><li><strong>Risk of domain logic encapsulation breach:</strong> Deferred query execution can lead to the blurring of business logic outside the domain model.</li><li><strong>Provider dependency:</strong><em> IQueryable&lt;T&gt;</em> implementation heavily depends on the database provider, which becomes especially important when using specific SQL functions not supported by all providers. Providers might interpret and optimize queries differently, leading to unexpected results or performance issues.</li></ul><p>Let&#39;s consider an example of implementing this approach in investment portfolio management.</p><h4><strong><em>Example #1</em></strong></h4><p>Our domain has an entity <em>Portfolio</em> — an aggregate root consisting of an entity<em> IntestmentTarget</em>. We were asked to build a query to get all active portfolios, including <em>InvestmentTarget&#39;s</em> data.</p><pre>public class Portfolio : AggregateRoot {<br>    public Guid Id { get; private set; }<br>    public bool IsActive { get; set; }<br>    public InvestmentTarget InvestmentTarget { get; set; }<br>}<br><br>public class InvestmentTarget : Entity {<br>    public Guid Id { get; private set; }<br>    public string Name { get; set; }<br>}</pre><p>In the <em>PortfolioRepository</em> class, the <em>GetActivePortfolios()</em> method forms and returns a query of type <em>IQueryable&lt;Portfolio&gt;</em>, allowing filtering and sorting conditions to be added before executing the query.</p><pre>public interface IPortfolioRepository {<br>    IQueryable&lt;Portfolio&gt; GetActivePortfolios();<br>}<br><br>public class PortfolioRepository : IPortfolioRepository {<br>    private readonly DbContext dbContext;<br><br>    public PortfolioRepository(DbContext dbContext) {<br>        this.dbContext = dbContext;<br>    }<br><br>    public IQueryable&lt;Portfolio&gt; GetActivePortfolios() {<br>        return dbContext.Set&lt;Portfolio&gt;()<br>            .Where(p =&gt; p.IsActive)<br>            .Include(p =&gt; p.InvestmentTarget);<br>    }<br>}</pre><pre>//consumer side<br>...<br>var activePortfolios = portfolioRepository.GetActivePortfolios().ToList();</pre><p>Now, let&#39;s move on to the <strong><em>List&lt;T&gt;</em></strong> approach.</p><h3>List&lt;T&gt;: Simplicity and Immediate Execution</h3><p>In this approach, repository methods return a <em>List&lt;T&gt;</em>, which ensures the immediate execution of the query. This method simplifies debugging and testing but limits flexibility and can lead to excessive data loading. Unlike <em>IQueryable&lt;T&gt;</em>, <em>List&lt;T&gt;</em> executes queries directly at the time of their call, simplifying debugging due to more predictable behavior but limiting the possibilities for dynamic query modification.</p><h4><strong>Advantages:</strong></h4><ul><li><strong>Full upfront loading:</strong> Using <em>List&lt;T&gt;</em> allows loading all data at once, which can be helpful in scenarios where all data is needed for further processing without additional database queries.</li><li><strong>Simplicity: </strong>Easy to use and understand, implying less complexity in query building. <em>List&lt;T&gt;</em> also provides convenience in working with in-memory data, as it represents a concrete collection of objects.</li></ul><h4>Disadvantages:</h4><ul><li><strong>Limited flexibility:</strong> New repository methods for different queries require explicitly defining each query, increasing code volume, and reducing scalability.</li><li><strong>Large data volume:</strong> This can lead to excessive loading, particularly relevant when working with large data volumes, where each collection item occupies significant memory space.</li><li><strong>Lack of lazy loading:</strong> Unlike <em>IQueryable&lt;T&gt;</em>, <em>List&lt;T&gt;</em> does not support lazy loading, meaning all data is loaded immediately, even if not needed, which can increase response time and system load.</li><li><strong>Performance issues with updates:</strong> If data in <em>List&lt;T&gt;</em> is frequently updated, it may require re-executing the query and reloading the entire collection, which can negatively impact application performance.</li></ul><p>To demonstrate, let&#39;s consider the use of <em>List&lt;T&gt;</em> in implementing <em>PortfolioRepository</em>, where immediate access to data is required without additional processing on the client side.</p><h4>Example #2</h4><p><em>PortfolioRepository</em> uses <em>List&lt;Portfolio&gt;</em> for the <em>GetActivePortfolios()</em> method in scenarios requiring immediate access to already filtered and prepared data.</p><pre>public interface IPortfolioRepository {<br>    List&lt;Portfolio&gt; GetActivePortfolios();<br>}<br><br>public class PortfolioRepository : IPortfolioRepository {<br>    private readonly DbContext dbContext;<br><br>    public PortfolioRepository(DbContext dbContext) {<br>        this.dbContext = dbContext;<br>    }<br><br>    public List&lt;Portfolio&gt; GetActivePortfolios() {<br>        return dbContext.Set&lt;Portfolio&gt;()<br>            .Where(p =&gt; p.IsActive)<br>            .Include(p =&gt; p.InvestmentTarget)<br>            .ToList();<br>    }<br>}</pre><pre>// consumer side<br>...<br>var activePortfolios = portfolioRepository.GetActivePortfolios();</pre><p>Let&#39;s now move on to the following approach: <strong>Specification Pattern</strong>.</p><h3>Specification Pattern: Clean Code and Reusability</h3><p>Using the<em> Specification Pattern</em>, queries are defined as separate classes, improving the domain model&#39;s description, code testability, and reuse of queries. However, this adds architectural complexity and can be excessive for simple tasks or applications.</p><h4>Advantages:</h4><ul><li><strong>Flexibility and Scalability:</strong> The <em>Specification Pattern</em> allows flexible and scalable management of queries, adapting them to different needs and changing conditions without altering the repository.</li><li><strong>Reusability:</strong> Enhances the testability and reuse of query logic. In addition to improving testability, this pattern is ideal for complex business rules where dynamically combining different specifications depending on the context is required.</li><li><strong>Better Code Organization:</strong> According to <em>DDD</em>, the pattern promotes better code organization, as the query logic is part of the domain logic.</li></ul><h4>Disadvantages:</h4><ul><li><strong>Overcomplication for Small Projects:</strong> In small projects or when working with simple data, the Specification Pattern may lead to unnecessary complexity in the architecture and codebase.</li><li><strong>Learning Curve:</strong> For developers encountering this pattern for the first time, additional time may be required to learn and understand its concepts, increasing the overall learning curve.</li><li><strong>Complexity in Query Optimization:</strong> Due to the complexity and abstraction introduced by the pattern, query optimization can become more challenging, especially when a deep understanding of database interactions or performance optimization is required.</li></ul><p>In the following example, the <em>Specification Pattern</em> is used for flexible query composition in the portfolio repository, allowing easy adaptation of data selection logic based on business requirements.</p><h4>Example #3</h4><p>In the example of <em>ActivePortfoliosWithDependenciesSpec</em>, the <em>Specification Pattern</em> is applied using the <a href="https://github.com/ardalis/Specification">Specification library</a> by Steve Smith (a.k.a Ardalis), centralizing the query logic in the domain project.</p><pre>public class ActivePortfoliosWithDependenciesSpec : Specification&lt;Portfolio&gt; {<br>    public ActivePortfoliosWithDependenciesSpec() {<br>        Query.Where(p =&gt; p.IsActive)<br>            .Include(p =&gt; p.InvestmentTarget);<br>    }<br>}<br><br>public interface IRepository&lt;T&gt; where T : class, IAggregateRoot {<br>    IEnumerable&lt;T&gt; GetPortfolios(ISpecification&lt;T&gt; spec);<br>}<br><br>public class Repository&lt;T&gt; : IRepository&lt;T&gt; where T : class, IAggregateRoot {<br>    // For detailed implementation of the Specification repository, look here: <br>    // https://github.com/ardalis/Specification<br>}</pre><pre>// consumer side<br>...<br>var spec = new ActivePortfoliosWithDependenciesSpec();<br>var activePortfolios = await portfolioRepository.SingleOrDefaultAsync(spec);</pre><p>Let&#39;s move on to the last approach: <strong>MediatR&#39;s Query Request</strong>.</p><h3>MediatR&#39;s Query Request: Clear Separation and Scalability</h3><p>The application of <em>MediatR</em> with the <em>CQRS</em> pattern separates queries and their handling, which combines well with other design patterns. However, it requires a deep understanding of <em>CQRS</em> and can lead to an additional increase in the codebase.</p><h4>Advantages:</h4><ul><li><strong>Following <em>DDD</em> and <em>CQRS</em>:</strong> A clear separation of responsibilities between forming and handling queries simplifies the application&#39;s scalability.</li><li><strong>Improved Application Responsiveness: </strong>Using <em>MediatR</em> in combination with <em>CQRS</em> can lead to more responsive user interfaces, as read queries and write commands are processed separately, reducing delays.</li><li><strong>Better Support for Asynchrony: </strong><em>MediatR</em> supports asynchronous query handlers, which can significantly improve the performance of applications, especially in networked or scalable systems.</li></ul><h4>Disadvantages:</h4><ul><li><strong>Requirement for Team Organization:</strong> Effective use of <em>MediatR</em> and <em>CQRS</em> often requires a well-organized team of developers and a clear separation of responsibilities, which can be problematic in small or less organized teams.</li><li><strong>Complication of Architecture: </strong>The increase in the amount of code and classes can lead to project maintenance complexity, especially in smaller teams, and can be excessive for simple projects.</li></ul><p>In the following example, <em>MediatR</em> separates calls according to <em>CQRS</em>, which was discussed in the article <a href="https://sharpassembly.medium.com/cqrs-repository-and-mediatr-65883d1a1fac">&quot;CQRS, Repository, and MediatR&quot;</a>.</p><h4>Example #4</h4><p>In <em>GetActivePortfoliosQueryHandler</em>, <em>MediatR</em> handles queries, clearly separating responsibilities between components.</p><pre>public class GetActivePortfoliosQuery : IRequest&lt;IEnumerable&lt;Portfolio&gt;&gt; { }<br><br>public class GetActivePortfoliosQueryHandler : IRequestHandler&lt;GetActivePortfoliosQuery, IEnumerable&lt;Portfolio&gt;&gt; {<br>    private readonly IPortfolioRepository portfolioRepository;<br><br>    public GetActivePortfoliosQueryHandler(IPortfolioRepository portfolioRepository) {<br>        this.portfolioRepository = portfolioRepository;<br>    }<br><br>    public async Task&lt;IEnumerable&lt;Portfolio&gt;&gt; Handle(GetActivePortfoliosQuery request, CancellationToken cancellationToken) {<br>        return await portfolioRepository.GetActivePortfolios();<br>    }<br>}</pre><pre>// consumer side<br>...<br>var activePortfolios = await mediator.Send(new GetActivePortfoliosQuery());</pre><h3>Practical Example</h3><p>While developing the individual investment tracking application <em>InWestMan</em>, I chose an approach based on using <em>IQueryable&lt;T&gt;</em> in the first iteration. This choice seemed convenient to me and provided flexibility with the ability to extract data from the database as needed and add additional sorting and filtering on the client side.</p><p>Initially, I did not consider the violation of <em>CQRS</em> principles to be a severe problem. However, when testing asynchronous changes of records from the client side, difficulties arose with organizing their integration. Over time, I discovered that the business logic for data extraction from the database was scattered throughout the project, contradicting the <em>DDD</em> architecture I was trying to follow. Some logic was embedded directly in the repository implementation, some was at the application level, and some aspects were now implemented in the web client. The only area where there was virtually no logic was the domain model.</p><p>In my project, the <em>Specification Pattern</em> is used for queries and <em>MediatR</em> for commands, such that all business logic is concentrated in the domain project. Each new Specification class is responsible for its query construction in the database. As a result, this approach not only simplified the original structure of the project but also enriched the domain model, as all necessary specifications are now concentrated in one place.</p><h3>Conclusion</h3><p>The choice of approach for reading data from the database is a crucial moment in designing the architecture of an application. It should be based on the analysis of the specific project&#39;s requirements. Each of the presented methods — <em>IQueryable&lt;T&gt;</em>, <em>List&lt;T&gt;</em>, <em>Specification Pattern</em>, and <em>MediatR</em> — has unique advantages, risks, and limitations that must be considered when solving specific tasks.</p><p><em>IQueryable&lt;T&gt;</em> is appropriate for scenarios requiring flexibility in forming queries on the client side, while <em>List&lt;T&gt;</em> suits scenarios where simplicity and immediate execution of queries are essential. The Specification Pattern is a powerful tool for creating clean and testable code, adhering to <em>DDD</em> principles, and is ideal for situations where business logic needs to be separated from data storage mechanisms. <em>MediatR</em> and the <em>CQRS</em> pattern provide a high degree of abstraction and separation of responsibilities, making them suitable for complex applications with advanced business logic and the need for scalability.</p><p>It&#39;s important to understand that the choice is not limited to a single approach and can combine several strategies depending on the development and expansion of the project. Experience from personal practice, as in the example with the InWestMan application, underscores the importance of flexibility and adaptability in choosing an approach. It also shows how the evolution of requirements can influence architectural decisions and their changes.</p><p><strong>Subscribe for more:</strong></p><p><a href="https://sharpassembly.medium.com/">https://sharpassembly.medium.com</a><br>https://t.me/SharpAssembly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLRYX8g_pdVFib8NLnvODQ.jpeg" /><figcaption>Credits: DALL·E generated</figcaption></figure><p>#DDD #CQRS #InWestMan</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12256b1fd606" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sharpassembly/choosing-a-data-reading-architecture-in-net-four-approaches-12256b1fd606">Choosing a Data Reading Architecture in .NET: Four Approaches</a> was originally published in <a href="https://medium.com/sharpassembly">SharpAssembly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CQRS, Repository, and MediatR in .NET]]></title>
            <link>https://medium.com/sharpassembly/cqrs-repository-and-mediatr-65883d1a1fac?source=rss-a27d5e81061b------2</link>
            <guid isPermaLink="false">https://medium.com/p/65883d1a1fac</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Kostiantyn Bilous]]></dc:creator>
            <pubDate>Sat, 09 Dec 2023 06:31:47 GMT</pubDate>
            <atom:updated>2024-02-18T17:08:50.523Z</atom:updated>
            <content:encoded><![CDATA[<p>The principles of <strong>CQRS</strong> (Command and Query Responsibility Segregation), which separate CRUD (Create, Read, Update, Delete) operations into <strong>Command</strong> and <strong>Query</strong>, are considered an effective design practice. They imply differentiating actions over Entities: reading data (Read) and modifying data (Create, Update, Delete). The main idea of CQRS is that read operations should not change the state of the database. In contrast, data modification operations should not return data to the client, except for the ID of created Entities (with Create) or a flag of successful operation execution (with Update, Delete).</p><p>The ideal implementation of CQRS involves using separate databases for reading and writing data, followed by their synchronization. Adhering to CQRS principles and separating Command and Query in the code, even at the single database level, enhances data integrity and simplifies code maintenance.</p><p>The <strong>Repository</strong> pattern, which creates an abstract layer for executing CRUD queries, is critical to achieving CQRS design. The repository interface defines which actions can be performed on domain objects, indicating the expected result. Furthermore, a stricter interface limited to read methods can be defined to prevent unwanted changes in the database state. Notably, the correct implementation of the Repository interface should be independent of client logic, allowing changes in repository implementation without affecting the existing code as long as the original interface remains unchanged.</p><p>In the .NET environment, the <a href="https://github.com/jbogard/MediatR"><strong>MediatR</strong> library</a>, which implements the Mediator pattern, is widely used. Its application facilitates the implementation of CQRS principles by creating separate Requests and corresponding RequestHandlers for each command and query. This isolates each call into a separate class, simplifying the logic in the calling class. Thus, the MediatR approach enriches the domain model in the DDD (Domain-Driven Design) architecture, expressing business logic through possible actions over domains.</p><p>A couple of weeks ago, I came across a <a href="https://enterprisecraftsmanship.com/posts/cqrs-commands-part-domain-model/">blog discussion</a> suggesting that MediatR commands should be considered part of the domain model, akin to Domain Events, and viewed as serializable method calls. Despite criticism that commands are processed at the application level and should belong to it, I tend to agree with the author that commands are part of the domain and describe permissible actions over it. Meanwhile, command handlers implemented at the application level should contain minimal business logic and act as orchestrators of command execution, with proper registration in the Dependency Injection (DI) container.</p><h3>Practical Example</h3><p>In the initial version of the InWestMan — a personal investment tracking application, the domain logic was inefficiently distributed: domain objects served only for data mapping through Entity Framework. In contrast, business logic was placed on domain services. This approach led to the &quot;anemic&quot; state of the domains, depriving them of any inherent logic, which I later realized was an antipattern known as the <a href="https://martinfowler.com/bliki/AnemicDomainModel.html">&quot;Anemic Domain Model&quot;</a>. The business logic was smeared across different application layers: constructors and validations with database calls were held in domain services, business logic in application services, and hardcoded queries in repository implementation. The hardcoded queries and handling requests for creating or modifying entities, which returned full objects, were particularly challenging. As a result, the code became a confusing &quot;zoo&quot; of approaches, making it extremely difficult to determine which object was the most relevant.</p><p>At the same time, introducing the MediatR library at work while developing new functionalities for a commercial product significantly improved the overall architecture and code cleanliness. Using MediatR commands to declare possible actions over domain objects and handlers at the application level for orchestrating calls to the database and other components led to a clear and understandable structure, explicitly defining actions that a client can perform over domains.</p><p>This new division significantly improved my understanding of CQRS and DDD, leading me to almost completely rewrite the InWestMan projects. To expand the application&#39;s functionality, I added a new command in the domain project and a corresponding method in the API controller. The command is created upon an API request and passed through a mediator for execution by a handler at the Application level, handling the technical side of the command. At the same time, the expansion of business logic occurs at the domain level. This approach allows me to develop new features without affecting old commands and their handlers. To add new functionality, I follow the vertical structure of &quot;Controller&quot; → &quot;Command&quot; → &quot;Handler&quot; → &quot;Repository&quot; → &quot;Domain,&quot; striving to make each level as &quot;thin&quot; as possible and lowering the business logic as much as possible.</p><h3>Conclusion</h3><p>Applying CQRS principles in programming significantly improves the code structure and facilitates adaptation and expansion. However, it is essential to understand that successful implementation of CQRS requires careful architecture planning at the initial stages and strict discipline in its maintenance throughout the development cycle. This approach might not be the most suitable for projects with a limited lifespan, such as one-off solutions or prototypes. However, for developing business applications with a complex domain structure and the potential for scaling and further development, CQRS represents a valuable investment of effort and resources at the early stages of the project.</p><p><em>Subscribe for more:</em></p><p><a href="https://sharpassembly.medium.com/"><em>https://sharpassembly.medium.com/</em></a><em><br></em><a href="https://t.me/SharpAssembly"><em>https://t.me/SharpAssembly</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fc-_BH1ry07LLEwJ817Bdg.jpeg" /><figcaption>Credits: DALL·E generated</figcaption></figure><p>#DDD #CQRS #InWestMan</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65883d1a1fac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sharpassembly/cqrs-repository-and-mediatr-65883d1a1fac">CQRS, Repository, and MediatR in .NET</a> was originally published in <a href="https://medium.com/sharpassembly">SharpAssembly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Entity, Value Object, and Aggregate Root in Domain-Driven Design]]></title>
            <link>https://medium.com/sharpassembly/entity-value-object-and-aggregate-root-in-domain-driven-design-0ce9402e4ad3?source=rss-a27d5e81061b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ce9402e4ad3</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kostiantyn Bilous]]></dc:creator>
            <pubDate>Sat, 02 Dec 2023 06:52:58 GMT</pubDate>
            <atom:updated>2023-12-02T07:08:06.363Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Entity, Value Object, and Aggregate Root in Domain-Driven Design</strong></p><p>Domain-Driven Design (DDD) is a programming approach that focuses not on technical implementation, but on forming a clear domain model. This model reflects the interaction of entities as understood by domain experts and helps focus on solving business problems.</p><p>The main elements of the domain model are Entity, Value Object, and Aggregate Root.</p><p>· <strong>Entity</strong> is an object with a unique identifier that changes over time—for example, a client account. Even if two accounts have the same balance and transaction history, they are considered different because they have different account numbers.</p><p>· <strong>Value Object</strong> is an object without an identifier, where two objects with the same state are considered the same—for example, a monetary sum. Two sums of 100 dollars each are considered the same, regardless of the transactions or accounts they are associated with.</p><p>· <strong>Aggregate Root</strong> is a special type of Entity that encapsulates a group of objects and manages their behavior. Access to internal objects is only possible through the Aggregate Root, ensuring the integrity and consistency of data—for instance, an investment portfolio. All operations, such as buying, selling, or transferring positions, are conducted through the portfolio, thus ensuring the management and integrity of accounting.</p><p><strong>Practical Example:</strong><br>In my project, <em>InWestMan</em>, during the development of an application for personal investment tracking, my understanding and application of these concepts gradually evolved. Initially, the domain model served as a simple mapping for Entity Framework without pronounced domain logic. In subsequent iterations, clear Aggregate Roots such as transactions and portfolios were identified, along with corresponding Entities and Value Objects. This improved the structure and cleanliness of the model, and encapsulation in Aggregate Roots ensured data integrity, limiting access to internal objects.</p><p><strong>Conclusion</strong>:<br>The DDD approach allows the creation of a structured and comprehensible domain model by dividing its components into different contexts, which are loosely coupled. This ensures the integrity of the domain, simplifies the implementation of complex domain logic, and contributes not only to the technical but also to the strategic development of projects.</p><p><em>Check for more:</em></p><p><em>https://sharpassembly.medium.com/<br>https://t.me/SharpAssembly</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wjeZAGZYUvmO5Y55T7aOhA.jpeg" /><figcaption>Credits: DALL·E generated</figcaption></figure><p>#DDD #InWestMan</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ce9402e4ad3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sharpassembly/entity-value-object-and-aggregate-root-in-domain-driven-design-0ce9402e4ad3">Entity, Value Object, and Aggregate Root in Domain-Driven Design</a> was originally published in <a href="https://medium.com/sharpassembly">SharpAssembly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>