DDD Patterns for Continuous Integration and Continuous Refactoring

After looking at how to refactor the database, it is now time to unlock the synergy between DDD and Continuous Integration/Continuous Deployment ( CI/CD ). Whether you’re refactoring legacy code or building new applications, you’ll learn how to harness the power of automation, modularity, and iterative design to deliver high-quality software that serves your domain effectively.

In this chapter, you will learn how to do the following:

  1. Bridge DDD and CI/CD practice to align business needs with technical delivery through frequent, reliable feedback loops
  2. Refactor bounded contexts using proven patterns such as splitting and merging to improve modularity and adapt to changing requirements
  3. Use automation and tooling to maintain code quality, reduce errors, and streamline your CI/CD pipelines

By the end of this chapter, you’ll have learned practical strategies to ensure your domain models and CI/CD workflows reinforce each other for long-term success.

Integrating DDD with CI/CD

CI/CD and refactoring are not practices strictly tied to DDD—at least not exclusively! In the early days of software development, practices often borrowed concepts from manufacturing, with methods such as the Waterfall model shaping both large-scale processes and smaller tasks such as integration. In the 1990s, engineers on the C3 project, led by Kent Beck, introduced eXtreme Programming ( XP ), which emphasized automation and frequent feedback as essential drivers of productivity in software engineering. By the 2000s, these principles extended into the realm of operations, giving rise to DevOps and automating many previously manual tasks. Automation enables teams to move faster and more confidently by providing reliable feedback to prevent unexpected issues. As a result, feedback loops and automation have become cornerstones of modern software development practices.

Like in the Whirlpool Process (we referred to this in Figure 2 .7 in the Problem and solution space section in Chapter 2 , Understanding Complexity: Problem and Solution Space ), DDD emphasizes a continuous cycling of learning, modeling, and refining the domain as new insights emerge. Such an iterative approach goes hand in hand with CI, where frequent integration with short feedback cycles is encouraged. While the Whirlpool Process focuses on adapting the domain model to evolving business needs, CI/CD ensures that these refinements are rapidly tested, validated, and deployed.

So, CI/CD is more than a technical practice; it is a discipline that enables teams to deliver software in smaller, safer, and more predictable increments. Through the continuous merging and testing of code changes, integration risks are reduced; confidence increases, and collaboration is fostered. It is, however, heavily dependent on the structure and clarity of the code base. That is why DDD complements CI/CD: aligning software structure with business intent means that changes can remain focused, isolated, and testable. In this way, DDD and CI/CD can reinforce each other in reducing the accelerating development while preserving long-term maintainability.

One of the critical pieces of such synergy comes from DDD’s notion of bounded contexts. Each bounded context defines a clear boundary of responsibility, making it easier to isolate and test individual parts of the system. This modular design simplifies testing, supports incremental deployment, and minimizes the risk of changes affecting unrelated parts of the application. By ensuring that bounded contexts evolve independently while maintaining consistency with the overall domain model, DDD reinforces CI/CD’s goal of a stable, continuously deployable code base.

Why CI/CD benefits from DDD

Modern software systems are complex, often comprising interconnected domains with competing priorities and evolving requirements. Without a clear strategy to manage this complexity, CI/CD can easily become a bottleneck. Large, tangled code bases make changes prone to errors, tests fragile, and deployments unpredictable.

DDD introduces principles and patterns that combat these challenges directly:

  1. Clear boundaries through bounded contexts : By partitioning the system into bounded contexts, each with a certain business focus, DDD ensures changes in one area of the system are less likely to affect another. This isolation is vital for CI/CD pipelines because it enables smaller pieces that can be independently integrated and tested.
  2. Explicit communication via domain events : DDD provides a clear call to domain events, which handle semantic business events; these improve communications in the domain model and act as natural integration points between contexts. In CI, these events provide simpler testing and debugging because system behavior becomes more predictable.
  3. Evolving models by refactoring continuously : The iterative nature of DDD marries well with the incremental approach of CI. Regular refinement of the models keeps the code base representative of the current understanding of the domain, reducing technical debt and preventing stagnation.

Bridging business and technology

In a nutshell, the integration between DDD and CI/CD is fundamentally about bridging the gap that exists between business needs and technical delivery. The iterative processes of CI/CD demand a code base that is not only technically sound but also reflects the increasing understanding of the domain. DDD facilitates this in the following ways:

  1. Ubiquitous language : Developers, domain experts, and stakeholders have a common language, meaning changes in code truly will represent business needs. This sets up the basis for trusted and meaningful CI/CD pipelines.
  2. Supporting incremental delivery : DDD allows system design around autonomous contexts such that teams can deliver value incrementally without compromising on the integrity of the overall system.

Setting up a feedback loop

One of the primary goals of CI/CD is to create a rapid feedback loop . When integrated with DDD, this loop becomes not just about technical correctness but also about domain alignment. Automated tests validate not only that the code works but also that it serves its intended purpose in the domain. Domain events, for instance, provide immediate feedback about business processes, helping teams quickly identify and address misalignments.

Figure 9 .1 shows how this loop works in practice:

Figure 9.1 – CI/CD loop

Figure 9 .1 – CI/CD loop

This feedback loop becomes a powerful tool for continuously refining both the technical architecture and the domain model. As teams adopt patterns for splitting and merging bounded contexts, described later in this chapter, they can be assured that each context evolves independently according to business priorities.

This concept is also reinforced when refactoring bounded contexts by applying patterns such as splitting or merging, as you will see in the next section.

Patterns and techniques for effective DDD refactoring

Refactoring is not just about cleaning up code. In a DDD context, it’s a way to ensure the system evolves alongside the business domain. Splitting bounded contexts is one of the most impactful techniques for aligning technical boundaries with shifting business needs. Effective refactoring in a DDD environment requires structured approaches to managing bounded contexts and refining domain models.

By exploring the patterns and techniques that support this process, you will see that they are the same as already discussed in the earlier chapters of this book. That’s because the fundamentals of DDD also apply beautifully to this aspect of refactoring.

As you know, bounded context is a fundamental DDD concept that encapsulates a consistent domain language and model. Over time, as business needs evolve, these contexts may require splitting, merging, or redefinition. In this subsection, we will cover two techniques for managing such transitions: splitting bounded contexts and merging bounded contexts .

Splitting bounded contexts

When a bounded context grows too large or begins serving conflicting purposes, splitting it into smaller, more focused contexts can improve clarity and maintainability. For this reason, we can leverage domain decomposition or context mapping

Domain decomposition

Domain decomposition involves breaking down the responsibilities of a bounded context into smaller, distinct parts that align with specific subdomains or business capabilities. This approach helps identify natural seams in the domain model, enabling the creation of new, smaller contexts that better reflect business requirements.

Firstly, you need to understand the current context. As you already know by now, the only effective way is to work with the domain experts to map the existing responsibilities, workflows, and data flows within the bounded context. Do note that you can use tools such as EventStorming (see the EventStorming subsection in Chapter 2 , Understanding Complexity: Problem and Solution Space , for a quick explanation) or domain storytelling to visualize how the current model operates.

Then, you can move on to identify subdomains by separating core subdomains from supporting and generic subdomains.

Look for areas with distinct business logic or teams that already work semi-independently. Find natural seams by examining where invariants (rules that must be enforced) are localized. These areas are prime candidates for new contexts. After that, assess boundaries defined by team ownership, user roles, or external dependencies and plan dependencies. You must decide how the split contexts will interact. For example, some may exchange domain events, while others may rely on APIs or asynchronous messaging.

For example, a shipping context in an e-commerce system might handle both route optimization and delivery tracking. Over time, these responsibilities could diverge significantly:

  • Route optimization could become its own context, focused on advanced algorithms and integrations with mapping services
  • Delivery tracking could be a separate context, concerned with customer-facing updates and integration with external logistics systems

To recap, the refactoring steps could be summarized as follows:

  1. Isolate related aggregates into smaller clusters.
  2. Introduce domain events to define clear communication between the new contexts.
  3. Gradually refactor dependent code to respect the new boundaries.

Context mapping

Context mapping visualizes the relationships between bounded contexts, offering insights into their interactions, dependencies, and potential conflicts. It is an essential tool for planning and executing a split.

The steps are straightforward. You start by identifying the contexts already interacting with the one being split and then map the existing relationships, such as shared kernel , partnership , or upstream/downstream . As you analyze the new split contexts, represent each new context on the map, highlighting its relationship to the existing system. For example, after splitting, one context might depend on domain events produced by another.

After that, you must redefine the interaction patterns by adjusting patterns to match the new architecture. For example, you might change tight coupling such as shared kernel to a looser integration such as published language and transform a dependency-heavy relationship such as conformist into a partnership that allows for more autonomy.

Lastly, you must always validate with the domain experts. Collaborate with them to be able to confirm that the new boundaries align with business needs and workflows.

For example, in a Customer Support context of a telecommunications system, the split might result in two new contexts:

  • Ticket Management : Focused on tracking customer support tickets and their lifecycle.
  • Knowledge Base : Responsible for managing and updating help articles.

The context map would show the following:

  • Ticket Management produces domain events (e.g., Ticket Closed ) consumed by Knowledge Base to trigger content updates
  • The two contexts share a customer ID but otherwise operate independently

Finally, remember to use anti-corruption layers to manage communication between the old and new contexts during the transition period (look at the ACL subsection in Chapter 3 , Strategic Patterns , for a refresher) and verify that the split contexts communicate effectively through well-defined domain events or APIs with well-written integration tests (refer to the Understanding tests and their role in refactoring section in Chapter 5 , Introducing Refactoring Principles , for an explanation of tests and their different types).

Splitting bounded contexts is a complex yet rewarding process that enhances system modularity and business agility. By leveraging domain decomposition and context mapping, teams can make informed decisions, ensuring a smooth evolution toward a more maintainable and scalable architecture.

Merging bounded contexts

Conversely, merging contexts may be necessary if boundaries are no longer meaningful or cause excessive friction. To merge contexts, you must first identify redundancies such as overlapping models, duplicate logic, or tight coupling between two contexts. Only then can you establish a new shared language and ensure the merged context adopts a unified ubiquitous language to eliminate inconsistencies. In short, the refactoring steps that you can then follow consist of consolidating aggregates into a shared model, deprecating redundant domain events and replacing them with shared ones, and lastly revisiting context maps to reflect the new, simplified structure.

A merge becomes necessary in scenarios such as when the domain models of two contexts have significant overlap, making their separation redundant. This often happens when different teams or phases of a project initially create boundaries that, over time, no longer reflect the current business landscape. Similarly, if two contexts frequently interact to the point that the integration overhead outweighs the benefits of separation, it is worth considering a merge. Changes in business strategy, such as consolidating operations or redefining team responsibilities, can also reveal opportunities for merging contexts that once served distinct purposes.

The process of merging begins with a thorough understanding of the existing contexts. The teams involved should analyze the responsibilities, domain models, and workflows of each context to identify overlaps and redundancies. Collaboration with domain experts is essential to uncover shared concepts and ensure the unified context aligns with the business’ needs. This step often involves documenting the interactions and dependencies between the contexts to understand how the merge will affect the system as a whole.

Once a clear picture of the current state emerges, you can define the unified context. This involves creating a single domain model that consolidates shared entities and concepts while eliminating duplications. Careful thought must be given to the new boundaries of the merged context, ensuring it encapsulates all relevant responsibilities without becoming a monolith. The merged context should maintain cohesion, focusing on a consistent set of business capabilities.

For example, consider a situation where the Warehouse context handles stock management and shipments, while the Sales context manages orders and payments. Initially, these contexts were distinct to allow focused development. Over time, however, the Warehouse context’s stock availability began to influence the Sales context’s ability to accept orders, creating a dependency. The frequent need for synchronization between these contexts led to bottlenecks and integration challenges. In such a scenario, merging Warehouse and Sales into a single context might simplify operations by providing a unified model for managing orders and stock. This new context could include a consistent invariant, such as ensuring a beer cannot be sold if it is out of stock.

The transition from separate to unified contexts should be gradual to reduce risks. During the initial stages, shared domain events can act as a bridge between the contexts, maintaining existing functionality while the unified domain model is developed. For example, the Sales context could continue to rely on domain events such as AvailabilityUpdated from the Warehouse context until a unified stock management system is ready. As the integration progresses, entities and business rules can be migrated incrementally into the new context, ensuring that each step aligns with the unified model.

Another important aspect of merging is redefining the relationships between the new unified context and other parts of the system. Upstream and downstream dependencies must be adjusted to reflect the new architecture. In the case of the Warehouse and Sales merge, external systems such as Customer Service would need to interact with the unified context to retrieve stock and order information. These changes require careful planning to avoid disruptions.

Validating the success of a merge involves extensive testing and collaboration with domain experts. The unified context must meet both technical and business expectations. Domain experts play a critical role in confirming that the new model aligns with the company’s workflows and goals. Testing ensures that the system’s performance and reliability remain unaffected during and after the transition.

For example, in the case of the merged Warehouse and Sales context, the team must validate that the unified model supports both backend operations, such as stock tracking, and customer-facing processes, such as order confirmations. Performance bottlenecks introduced by the merge, such as slower order processing due to combined responsibilities, must be identified and addressed.

Merging bounded contexts is a strategic decision that requires careful planning and execution. When done correctly, it reduces the complexity of managing separate systems, streamlines communication, and ensures the architecture remains aligned with the domain’s realities. By focusing on creating a cohesive, well-defined context, teams can enhance both technical efficiency and business agility.

While the patterns and techniques discussed in this section provide a strong foundation for effective DDD refactoring, maintaining a well-aligned domain model requires an ongoing commitment to continuous refactoring.

Continuous refactoring within a DDD context

The nature of DDD makes continuous refactoring particularly important because domains are dynamic. Business needs change, markets shift, and organizational strategies evolve. In a static code base, these changes can lead to misalignment between the system’s implementation and the real-world processes it aims to model. Left unchecked, this drift introduces inefficiencies, impairs communication, and hampers agility. Continuous refactoring addresses this by embracing change as a natural part of software development.

At its heart, continuous refactoring in a DDD context is about weaving domain refinement into the fabric of day-to-day development. This means refactoring is not reserved for isolated cleanup phases; it happens every time a new feature is introduced, a bug is fixed, or a domain concept is clarified. For example, when a domain expert provides a new insight into how a business rule operates, the development team should immediately reflect this understanding in the domain model, ensuring that the system continues to accurately represent the business.

To enable continuous refactoring, robust practices must be in place. One key aspect is maintaining a clear and well-articulated ubiquitous language. As teams engage with domain experts and refine their understanding of the domain, this shared language evolves. Continuous refactoring ensures that the code base evolves in tandem, incorporating changes to entities, aggregates, and domain events to reflect the updated language. This process prevents inconsistencies and ensures that the code remains a reliable reference for the domain.

Another critical enabler is the use of automation to support frequent and safe iterations. Automated tests, particularly those focused on business logic, are indispensable in a DDD context. These tests act as a safety net, allowing developers to refactor with confidence. By capturing the intent and constraints of the domain, automated tests help ensure that refactoring efforts do not inadvertently disrupt functionality. Additionally, tools such as linters, static analyzers, and dependency scanners can proactively identify code smells or architectural drift, prompting timely intervention.

Continuous refactoring also thrives on collaboration. In a DDD environment, it is not solely a technical activity, it is inherently tied to domain exploration. Developers must work closely with domain experts to identify areas of the model that need refinement. These discussions often uncover opportunities to simplify complex workflows, consolidate overlapping concepts, or eliminate redundancies. For instance, a domain expert might reveal that two similar-sounding domain events—such as OrderPlaced and OrderInitiated —are effectively describing the same business action. Continuous refactoring would merge these events into one, reducing ambiguity and enhancing clarity.

In practice, continuous refactoring requires teams to be mindful of the boundaries of their bounded contexts. Misaligned or poorly understood boundaries often introduce friction, leading to unnecessary coupling or inefficiencies. By regularly revisiting these boundaries, teams can make minor adjustments to keep them relevant. This might involve redefining the scope of a context to better fit current business capabilities or restructuring interactions between contexts to reflect updated workflows.

An essential outcome of continuous refactoring is that it prevents architectural decay. Over time, even well-designed systems can accumulate technical and conceptual debt as new features are added or shortcuts are taken to meet deadlines. By treating refactoring as an integral part of feature development, teams ensure that the system does not degrade under the weight of these changes. For example, when implementing a new feature, developers can seize the opportunity to clarify ambiguous domain concepts, simplify convoluted code paths, or replace outdated patterns with more effective alternatives.

One significant challenge in continuous refactoring is balancing improvement efforts with delivery timelines. Teams must prioritize changes that provide the most value, ensuring that refactoring efforts align with business priorities. Small, incremental adjustments are often the most effective approach, as they minimize disruption while delivering steady progress. This incrementalism aligns well with agile practices, where frequent iterations allow for rapid feedback and course correction.

Continuous refactoring within a DDD context is not just about maintaining code quality but is about preserving the connection between the system and the business it serves. By embedding this practice into daily workflows, teams can ensure that the software remains a faithful and effective representation of the domain, capable of adapting to whatever challenges and opportunities the future holds. This commitment to ongoing refinement transforms refactoring from a reactive activity into a proactive strategy for long-term success.

To support continuous refactoring in a DDD context, leveraging the right automation and tooling is essential for maintaining efficiency and consistency. We will discuss this next.

Automation and tooling

Automation and tooling are the backbone of modern software development practices, and their importance grows exponentially when applying DDD within a CI/CD pipeline. While DDD provides strategic and tactical patterns for designing robust systems, automation ensures these patterns are implemented efficiently and consistently across the development lifecycle. From code generation and automated testing to infrastructure as code and deployment pipelines, the right tools not only enhance productivity but also reduce human error, enabling teams to focus on solving domain problems. In this section, we are going to explore the tools and automation practices that bring DDD and CI/CD to life, ensuring smooth integration, testing, and deployment at scale.

At the heart of this synergy lies the source code repository , which acts as much more than a simple storage medium for code. It serves as the foundation for collaboration, traceability, and automated workflows, enabling the seamless orchestration of every step in the CI/CD pipeline.

Platforms such as GitHub , GitLab , Bitbucket , and Azure DevOps , to name a few, have become full-blown tools to support and automate the CI/CD pipeline. All of them offer a location for online code storage and capabilities for issue tracking and CI/CD.

The first platform to provide developers with an integrated CI/CD system, beyond just source control, was GitLab. GitLab introduced its CI/CD system in 2015, offering a fully integrated solution that allowed developers to manage both source code and the entire development lifecycle, from automated testing to deployment. This was innovative compared to platforms such as GitHub and Bitbucket at the time, which required external tools (such as Jenkins , Travis CI , or CircleCI ) to handle CI/CD workflows.

GitLab’s CI/CD integration was particularly advantageous for the following reasons:

  • It enabled the configuration of build, test, and deploy pipelines directly through a YAML file in the repository
  • It provided a seamless, centralized experience without the need for external tools
  • It was open source and available in a self-hosted version as well

Later, other platforms, such as GitHub (with GitHub Actions ), Bitbucket (with Bitbucket Pipelines ), Azure DevOps (with Azure Pipelines ), and AWS (with AWS CodePipeline ), introduced their own integrated CI/CD systems to offer similar capabilities.

All these platforms exemplify this critical role by providing tools for managing source code while also acting as a hub for automation, integration, and much more (i.e.: Kanban boards, tickets, etc.). Through features such as branching, pull requests, and code reviews, they facilitate a CI/CD workflow where teams can collaborate efficiently and maintain high-quality code standards.

So, the repository becomes not just a tool but an enabler of streamlined development practices, where every aspect of software delivery, from ideation to production, is tightly integrated and continuously optimized.

Along with unit tests, integration tests, and so on, an important tool for code quality is SonarQube ( https://www.sonarsource.com). It is a powerful open source tool for maintaining and improving code quality by examining source code and delivering detailed insights and reports on various quality metrics for your project. By integrating both static and dynamic analysis techniques, SonarQube allows teams to track and enhance code quality consistently throughout the development lifecycle.

Static code analysis is meant to detect bugs, vulnerabilities, code smells, and duplications across various programming languages. The key features that SonarQube offers are as follows:

  • Code quality gates : Enforces standards to ensure that code meets quality requirements before deployment
  • Multi-language support : Supports over 25 programming languages, such as Java, Python, JavaScript, and C#
  • Integration : Works seamlessly with CI/CD pipelines, DevOps tools (e.g., Jenkins, GitLab, GitHub, Azure DevOps), and IDEs
  • Security : Detects security vulnerabilities such as SQL injection and cross-site scripting ( XSS )
  • Custom rules : Enables custom rules for specific project requirements

As a result of all these features, consequently, you end up with the following benefits:

  • Improved code quality : Continuous monitoring helps developers produce cleaner, more maintainable code
  • Reduced technical debt : Identifies areas that need refactoring to reduce long-term maintenance costs
  • Enhanced security : Early detection of vulnerabilities reduces risks in production
  • Team collaboration : Promotes shared standards and accountability across teams

SonarQube can be introduced as part of the development pipeline, ensuring every piece of code aligns with the organization’s quality and security standards.

SonarQube and GitLab example

The following code is an example of a complete workflow for GitLab that also takes advantage of SonarQube features:

stages:
  - cleanup
  - build
  - test
  - sonarqube
  - deploy
cleanup:
  stage: cleanup
  script:
    - docker system prune --all --force
  tags:
    - shell
build:
  stage: build
  image: mcr.microsoft.com/dotnet/sdk:9.0
  script:
    - dotnet build
  tags:
    - docker
test:
  stage: test
  script:
    - dotnet test --collect:"XPlat Code Coverage;Format=opencover" --results-directory TestResults
  artifacts:
    paths:
      - TestResults/
      - TestResults/**/*.trx
      - TestResults/**/coverage.opencover.xml
  tags:
    - docker
sonarqube-check:
  stage: sonarqube
  image: mcr.microsoft.com/dotnet/sdk:9.0
  variables:
    SONAR_USER_HOME: "${CI_PROJECT_DIR}/.sonar"  # Defines the location of the analysis task cache
    GIT_DEPTH: "0"  # Tells git to fetch all the branches of the project, required by the analysis task
  cache:
    key: "${CI_JOB_NAME}"
    paths:
      - .sonar/cache
  script:
    - "apt-get update"
    - "apt-get install --yes default-jdk"
    - "dotnet tool install --global dotnet-sonarscanner"
    - "export PATH=\"$PATH:$HOME/.dotnet/tools\""
    - "dotnet sonarscanner begin /k:\"iris-poc-api\" /d:sonar.login=\"$SONAR_TOKEN\" /d:sonar.host.url=\"$SONAR_HOST_URL\" /d:sonar.cs.opencover.reportsPaths=\"TestResults/**/coverage.opencover.xml\""
    - "dotnet build"
    - "dotnet sonarscanner end /d:sonar.login=\"$SONAR_TOKEN\""
  allow_failure: true
  tags:
    - docker
deploy:
  stage: deploy
  script:
    - deploy commands (any container registry, ftp, etc.)...
  tags:
    - deploy

In the preceding code, the first stage is cleanup , which in this case consists of cleaning the Docker environment. This is done with docker system prune --all –force , which forces the deletion of all the unused images, containers, and networks.

The second stage, build , proceeds to build the solution, and then the following stage, test , runs the tests. You read about the importance of testing in the Understanding tests and their role in refactoring section in Chapter 5 , and it is important to understand that if any of the tests fail the deployment process will fail and, as a result, nothing must be deployed in production till all tests are passed.

If the tests pass, the script moves on to the sonarqube stage, which evaluates the quality of your software. SonarQube allows you to set specific test coverage thresholds to ensure that your code base meets quality standards. It analyzes your project’s test results and measures how much of the code is exercised by your test cases, typically displayed as a percentage. You can configure coverage goals in your quality gate, such as requiring at least 80% coverage. If the coverage falls below the set threshold, SonarQube will flag it as a failure, prompting developers to improve test coverage before merging or deploying the code. This helps maintain robust testing practices and ensures higher code reliability.

Finally, the last stage, deploy , kicks in and our application is deployed in staging or production depending on the rules engaged.

GitHub Actions example

The following is another example but with GitHub Actions:

name: 🚀 BrewUp.Rest deploy pipeline
on:
  workflow_dispatch:
  push:
    paths:
      - './**'
    branches:
      - develop
    tags:
      - '*'
env:
  SOLUTION_PATH: ./BrewUp.Rest.sln
  DOCKERFILE_PATH: ./BrewUp.Rest/Dockerfile
  STAGING_MY_CLOUD_PROVIDER_APP: BrewUp-staging
  PRODUCTION_MY_CLOUD_PROVIDER_APP: BrewUp-staging
  IMAGE_NAME: ${{ github.repository }}-BrewUp
  DOCKER_CONTEXT_PATH: ./
jobs:
  build_and_test:
    name: 🛠 Build and Test
    runs-on: ubuntu-latest
    steps:
      - name: 🚚 Get latest code
        uses: actions/checkout@v4
      - name: 🔧 Setup .NET Core
        uses: actions/setup-dotnet@v4
      - name: 📥 Restore dependencies
        run: dotnet restore ${{ env.SOLUTION_PATH }}
      - name: 🔨 Build
        run: dotnet build ${{ env.SOLUTION_PATH }}
      - name: 🧪 Run tests
        run: dotnet test ${{ env.SOLUTION_PATH }}
  build_and_push_staging_image_amd64:
    name: 🐳 Build and push develop amd64 Docker image to GitHub Container Registry
    runs-on: ubuntu-latest
    needs: build_and_test
    if: startsWith(github.ref, 'refs/heads/develop')
    steps:
      - name: 🚚 Get latest code
        uses: actions/checkout@v4
      - name: 🔑 Login to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.REGISTRY_HUB_SECRET }} 
      - name: 📤 Build and push image
        uses: docker/build-push-action@v6
        with:
          context: ${{ env.DOCKER_CONTEXT_PATH }}
          file: ${{ env.DOCKERFILE_PATH }}
          platforms: linux/amd64
          push: true
          tags: ghcr.io/${{ env.IMAGE_NAME }}:develop
         
  build_and_push_production_image:
    name: 🐳 Build and push tag Docker image to GitHub Container Registry
    # Like staging. Here is the configuration for the production environment
  deploy_staging:
    name: 🚀 Deploy to Staging
    runs-on: ubuntu-latest
    needs: build_and_push_staging_image_amd64
    if: startsWith(github.ref, 'refs/heads/develop')
    steps:
      - name: 🌊 Deploy to my cloud provider
        uses: my_cloud_provider/[email protected]
        with:
          app_name: ${{ env.STAGING_MY_CLOUD_PROVIDER_APP }}
          token: ${{ secrets.MY_CLOUD_PROVIDER_TOKEN }}
  deploy_production:
    name: 🚀 Deploy to Production
    # Like staging. Here is the configuration for the production environment
  notify_on_failure:
    name: ❗⚠ Notify Microsoft Teams of deployment failure
    runs-on: ubuntu-latest
    needs: [build_and_test, build_and_push_staging_image_amd64, build_and_push_production_image, deploy_staging, deploy_production]
    if: |
      always() &&
      (
        needs.build_and_test.result == 'failure' ||
        needs.build_and_push_staging_image_amd64.result == 'failure' ||
        needs.build_and_push_production_image.result == 'failure' ||
        needs.deploy_staging.result == 'failure' ||
        needs.deploy_production.result == 'failure'
      )
    steps:
      - name: 📫 Send Microsoft Teams Notification
        uses: jdcargile/[email protected]
        with:
          github-token: ${{ github.token }}
          ms-teams-webhook-uri: ${{ secrets.MS_TEAMS_WEBHOOK_URL }}
          notification-summary: ${{ github.workflow }} failed by deploying ${{ github.ref_name }}, check the workflow run for more information.
          notification-color: dc3545
          timezone: Europe/Rome
          verbose-logging: true

The preceding code comprises a more complex example, but we will not delve into explaining all the steps because it is out of this book’s scope. However, this example basically follows the same stages explained in the GitLab example we covered before this one and, as a plus, includes an example of integration with Microsoft Teams for failures.

Summary

In this chapter, you discovered how integrating DDD with CI/CD can transform the way you build and maintain software. You explored how these methodologies complement each other, helping you deliver systems that are modular, aligned with business goals, and easy to evolve. By combining DDD’s strategic insights with CI/CD’s technical rigor, you’ve gained tools to tackle complexity while fostering agility and maintainability.

Here’s what you learned:

  • How DDD enhances CI/CD workflows, enabling frequent, safe updates through modularity and alignment with domain models
  • Techniques for refactoring bounded contexts
  • The importance of automation and tools, such as SonarQube and CI/CD pipelines, in ensuring code quality and seamless delivery

With these insights, you’re now equipped to create resilient systems that keep pace with both technical and business demands.

Remember that effective DDD refactoring is not just about improving code; it’s about evolving systems in harmony with the domain. By mastering these patterns and techniques, you can ensure your system remains both technically robust and aligned with business needs.

The next chapter is about microservices architecture and when it makes sense to move your perfectly working monolith to a more complex system such as one made of microservices.

Get this book’s PDF version and more

Scan the QR code (or go to packtpub.com/unlock ). Search for this book by name, confirm the edition, and then follow the steps on the page.

A qr code on a white background
AI-generated content may be incorrect.

A white text on a black background
AI-generated content may be incorrect.

Note: Keep your invoice handy. Purchases made directly from Packt don’t require an invoice.