.Net – CMARIX QandA https://www.cmarix.com/qanda Thu, 18 Sep 2025 13:32:00 +0000 en-US hourly 1 https://wordpress.org/?v=6.9 How Do You Automate Microservices CI/CD Using GitHub Actions? https://www.cmarix.com/qanda/aspnet-microservices-ci-cd-github-actions/ https://www.cmarix.com/qanda/aspnet-microservices-ci-cd-github-actions/#respond Thu, 18 Sep 2025 13:31:58 +0000 https://www.cmarix.com/qanda/?p=2263 In a microservices setup, each service lives in its own world—its own codebase, dependencies, and release cycle. That independence is powerful, but it also demands a smart automation strategy. GitHub Actions provides a method to automate the entire CI/CD pipeline for each service—letting you build, test, and deploy without manual work or tangled scripts. Here’s […]

The post How Do You Automate Microservices CI/CD Using GitHub Actions? appeared first on CMARIX QandA.

]]>
In a microservices setup, each service lives in its own world—its own codebase, dependencies, and release cycle. That independence is powerful, but it also demands a smart automation strategy. GitHub Actions provides a method to automate the entire CI/CD pipeline for each service—letting you build, test, and deploy without manual work or tangled scripts. Here’s how it works and why it matters.

What Is CI/CD for Microservices with GitHub Actions?

CI/CD for Microservices using GitHub Actions automates:

  • CI (Continuous Integration): Build, test, and validate code on every commit or PR
  • CD (Continuous Deployment/Delivery): Automatically deploy microservices to environments (e.g., Docker, Kubernetes, Azure, AWS)

In a microservices architecture, each service has its own pipeline and can be independently deployed.

Why Use GitHub Actions for Microservices?

  • Fast Feedback: Detect issues early during code integration
  • Independent Deployment: Independent Deployment: Each standalone service can be deployed without it affecting others
  • Consistency: Automation ensures every build/test/deploy is done the same way
  • Save Time: No need for manual builds/deployments
  • Scalability: Works for 2 or 50+ services

Step-by-Step: GitHub Actions CI/CD Workflow

Step 1: Create product-service.yml

name: CI/CD - Product Service

on:
  push:
    paths:
      - 'ProductService/**'
      - '.github/workflows/product-service.yml'
    branches:
      - main

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout code
      uses: actions/checkout@v3

    - name: Set up .NET SDK
      uses: actions/setup-dotnet@v3
      with:
        dotnet-version: '7.0.x'

    - name: Restore dependencies
      run: dotnet restore ProductService/ProductService.csproj

    - name: Build
      run: dotnet build ProductService/ProductService.csproj --no-restore --configuration Release

    - name: Test
      run: dotnet test ProductService/ProductService.csproj --no-restore --verbosity normal

    - name: Build Docker Image
      run: docker build -t myregistry/product-service:latest ProductService/

    - name: Login to Docker Hub
      uses: docker/login-action@v2
      with:
        username: ${{ secrets.DOCKER_USERNAME }}
        password: ${{ secrets.DOCKER_PASSWORD }}

    - name: Push Docker Image
      run: docker push myregistry/product-service:latest

Store Docker credentials in GitHub Secrets:

  • DOCKER_USERNAME
  • DOCKER_PASSWORD

Step 2: Repeat for Other Services

Create a similar file like order-service.yml under .github/workflows for OrderService.

Change:

  • Project path
  • Docker image name

Optional: Deploy to Kubernetes (AKS, EKS, GKE)

Add below steps after docker push:

- name: Set up kubectl
  uses: azure/setup-kubectl@v3
  with:
    version: 'v1.28.0'

- name: Deploy to Kubernetes
  run: |
    kubectl apply -f k8s/product-deployment.yaml
    kubectl rollout status deployment/product-service

You’ll need:

  • Cluster kubeconfig (store as secret or use GitHub OIDC + Azure/AWS IAM roles)
  • Helm or kubectl files per service

Advantages:

  • Per-Service Pipelines: Isolate failures and deploy services independently
  • Faster Releases: Auto-triggered builds/deployments
  • Platform Flexibility: Deploy to Docker Hub, AKS, EKS, or VMs
  • Secure: Secrets, access tokens, and fine-grained control
  • Reusable: Create reusable composite actions for shared steps

Disadvantages

  • Repetition: Separate files for each microservice can cause duplication
  • More Config: Each service requires Dockerfile, YAML, and deploy scripts
  • Complexity: Managing secrets, rollbacks, and debugging pipelines
  • Coupled Environments: If staging/prod deploys aren’t isolated properly, bugs can propagate fast

Best Practices

  • Modularization: One YAML per service
  • Reusability: Use GitHub composite actions for common steps
  • Secrets: Use GitHub Secrets or Azure Key Vault integration
  • Artifacts: Push images with version tags (not just latest)
  • Notifications: Add Slack/Teams/GitHub PR status for visibility
  • Rollback: Have rollback steps using Helm or Deployment strategies

Conclusion

If you’re running microservices, you need CI/CD that scales with you. GitHub Actions offers a flexible way to build isolated pipelines per service, without overcomplicating your DevOps. Start small, build a YAML for one service, keep your secrets clean, and expand from there. As your architecture grows, you’ll want experienced hands in your corner. This is where hiring .NET developers can make all the difference in keeping your pipelines clean, secure, and production-ready.

The post How Do You Automate Microservices CI/CD Using GitHub Actions? appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/aspnet-microservices-ci-cd-github-actions/feed/ 0
How to Perform Unit and Integration Testing in Modular Monoliths (.NET)? https://www.cmarix.com/qanda/unit-integration-testing-modular-monolith-dotnet/ https://www.cmarix.com/qanda/unit-integration-testing-modular-monolith-dotnet/#respond Thu, 18 Sep 2025 13:13:52 +0000 https://www.cmarix.com/qanda/?p=2258 Modular monoliths in .NET let you structure your application as distinct modules like Product, Order, and User without breaking it into separate services. Testing in this setup isn’t just helpful, it’s necessary. Unit tests are important to check how each module behaves in isolation, while integration tests are important to see if they work together […]

The post How to Perform Unit and Integration Testing in Modular Monoliths (.NET)? appeared first on CMARIX QandA.

]]>
Modular monoliths in .NET let you structure your application as distinct modules like Product, Order, and User without breaking it into separate services. Testing in this setup isn’t just helpful, it’s necessary. Unit tests are important to check how each module behaves in isolation, while integration tests are important to see if they work together as intended in real scenarios.

Types of Tests in Modular Monolith

Test TypeWhat it TestsScope
Unit TestIndividual classes/methodsInternal logic
Integration TestInteraction between modules or with real databaseSystem workflows
End-to-End Test (optional)Full app (UI/API to DB)External behavior

Example App Folder Structure

MyApp/
├── Modules/
│   ├── Product/
│   │   ├── ProductService.cs
│   │   └── ProductRepository.cs
│   ├── Order/
│   │   └── OrderService.cs
├── API/
│   └── Controllers/
├── Tests/
│   ├── UnitTests/
│   └── IntegrationTests/

How to Conduct Unit Testing in Modular Monolith .NET (Step-by-Step)

Step 1: Add xUnit and Moq to your test project

dotnet add package xunit
dotnet add package Moq

Step 2: Create Unit Test for Product Module

ProductService.cs

public class ProductService
{
    private readonly IProductRepository _repo;
    public ProductService(IProductRepository repo)
    {
        _repo = repo;
    }

    public Product GetById(int id) => _repo.GetById(id);
}

ProductServiceTests.cs

public class ProductServiceTests
{
    [Fact]
    public void GetById_ShouldReturnProduct()
    {
        // Arrange
        var mockRepo = new Mock<IProductRepository>();
        mockRepo.Setup(x => x.GetById(1)).Returns(new Product { Id = 1, Name = "Test" });

        var service = new ProductService(mockRepo.Object);

        // Act
        var result = service.GetById(1);

        // Assert
        Assert.NotNull(result);
        Assert.Equal("Test", result.Name);
    }
}

Integration Testing in Modular Monolith (Step-by-Step)

Step 1: Add Required NuGet Packages

dotnet add package Microsoft.AspNetCore.Mvc.Testing
dotnet add package Microsoft.EntityFrameworkCore.InMemory
dotnet add package FluentAssertions

Step 2: Create In-Memory Test Server

 ProductIntegrationTests.cs

public class ProductIntegrationTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly HttpClient _client;

    public ProductIntegrationTests(WebApplicationFactory<Program> factory)
    {
        _client = factory.CreateClient(); // In-memory test server
    }

    [Fact]
    public async Task GetProductById_ReturnsProduct()
    {
        // Act
        var response = await _client.GetAsync("/api/products/1");
        response.EnsureSuccessStatusCode();

        var json = await response.Content.ReadAsStringAsync();
        var product = JsonConvert.DeserializeObject<Product>(json);

        // Assert
        product.Should().NotBeNull();
        product.Id.Should().Be(1);
    }
}

Purpose: This tests the real behavior of the app, with routing, controllers, and DB (in-memory).

Step 3: Configure In-Memory DB in Program.cs for testing

if (app.Environment.IsEnvironment("Testing"))
{
    builder.Services.AddDbContext<AppDbContext>(options =>
        options.UseInMemoryDatabase("TestDb"));
}

Or override it using WebApplicationFactory<T> in your test setup.

Best Practices for all Testing in Modular Monolith

AspectRecommendation
Unit TestsFast, mock dependencies, and cover edge cases
Integration TestsUse TestServer, real or in-memory databases
FolderingOrganize tests by module for clarity
Test BoundariesVerify communication between modules is correct
IsolationClean the database before each integration test
PerformanceKeep integration tests fewer, but focused and meaningful
NamingFollow naming like ProductServiceTests.cs or OrderIntegrationTests.cs

Final Thought

Unit tests help confirm that each module works as intended, while integration tests ensure different modules interact properly in real-world scenarios. If you’re building a modular monolith and want reliable, scalable testing strategies, it’s a smart move to hire .NET developers who understand how to balance isolation with real-world validation. That’s how you keep your application modular, maintainable, and production-ready.

The post How to Perform Unit and Integration Testing in Modular Monoliths (.NET)? appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/unit-integration-testing-modular-monolith-dotnet/feed/ 0
What Are The Differences Between Modular Monolith Vs Microservices in .NET: When To Choose What? https://www.cmarix.com/qanda/modular-monolith-vs-microservices-dotnet/ https://www.cmarix.com/qanda/modular-monolith-vs-microservices-dotnet/#respond Thu, 18 Sep 2025 12:10:41 +0000 https://www.cmarix.com/qanda/?p=2253 Choosing between a modular monolith and microservices isn’t just a technical decision, it’s a strategic one. Each architecture serves different stages of a product’s lifecycle, different team sizes, and different scalability needs. If you are building a new .NET app from scratch, or planning to scale it, you should know the trade-offs and strengths of […]

The post What Are The Differences Between Modular Monolith Vs Microservices in .NET: When To Choose What? appeared first on CMARIX QandA.

]]>
Choosing between a modular monolith and microservices isn’t just a technical decision, it’s a strategic one. Each architecture serves different stages of a product’s lifecycle, different team sizes, and different scalability needs. If you are building a new .NET app from scratch, or planning to scale it, you should know the trade-offs and strengths of both the methods. This can help you avoid massive rewrite expenses down the road:

What is a Modular Monolith

A modular monolith is an architectural choice where your application is built as a single deployment unit, but it’s structured internally as independent, loosely-coupled modules with well-defined boundaries. 

Think of it as a monolith with a clean architecture, it has modules separated logically, but they run in the same process.

What are Microservices

Microservices architecture involves breaking the application into independent, small services. Each service:

  • Owns its data
  • Has its own deployment pipeline
  • Communicates with others via APIs (usually HTTP or messaging)

Think of each microservice as a mini-application with complete independence.

PurposeModular MonolithMicroservices
Simplified internal structureYesNot ideal
Independent scaling of featuresNot idealYes
Team autonomy for featuresPartialFull
Better for early-stage/startupsYesComplex for small teams
Deployment flexibilityOne unitDeploy individually
Clear module boundariesYesYes

Ecommerce System Example with Code Snippets

Modular Monolith Example

You build an app with the following internal modules:

  • UserModule
  • ProductModule
  • OrderModule
  • PaymentModule

They share the same:

  • Database
  • Codebase
  • Deployment pipeline

Each module communicates internally via services/interfaces, but everything is packaged as a single deployable unit (e.g., a .NET Web API).

// ProductModule service
public class ProductService
{
    public Product GetById(int id) { ... }
}

Microservices Example

You break the app into:

  • UserService (runs on port 5001)
  • ProductService (runs on port 5002)
  • OrderService (runs on port 5003)
  • PaymentService (runs on port 5004)

Each service:

  • Has its own database
  • Is deployed independently
  • Communicates over HTTP (e.g., REST)

Example API Call:

GET http://product-service/api/products/1

Advantages of Monolith Architecture

  • Easier to Develop: simpler architecture for small/medium teams
  • Easy Debugging: All logic runs in one process, easy to trace bugs
  • Easier Testing: End-to-end testing is simpler
  • Faster Development: Less infrastructure overhead
  • Cost Effective: No need for cloud-native orchestration (e.g., Kubernetes)

Advantages of Microservices Architecture

  • Independent Deployment: Services can be deployed, versioned separately
  • Scalable: Each service can scale horizontally as needed
  • Team Autonomy: Teams can own and deliver microservices independently
  • Technology Flexibility: Each service can use a different stack
  • Fault Isolation: Failure in one service doesn’t crash the entire app

Disadvantages of Monolith Architecture

  • Single Point of Failure: If one module crashes, entire app may go down
  • Harder to Scale Selectively: Can’t scale a single module independently
  • Tight Coupling Risk: Without discipline, modules may become tightly coupled
  • Deployment Size: Always deploy everything, even for small changes

Disadvantages of Microservices Architecture

  • Complexity Overhead: Requires handling service discovery, communication, retries, etc.
  • DevOps Maturity Needed: CI/CD, monitoring, logging, and infrastructure automation are a must
  • Communication Overhead: Services need to communicate over the network (can cause latency)
  • Debugging Difficulty: Distributed tracing is complex
  • Data Consistency: Maintaining ACID across services is hard

When to Choose Monolith vs Microservices in .NET

ConditionChoose Modular MonolithChoose Microservices
Startup / MVPYesNo
Small to mid-size appYesNot Worth It
Team size < 5-10YesToo Complex
Growing enterprise systemMaybeYes
Independent scaling needsNoYes
Separate team ownership per moduleHardEasy
DevOps maturityMinimalMust be High

Start with a modular monolith to reduce complexity. Move to microservices only when your app outgrows the monolith and you need independent deployment, team scaling, or horizontal scaling of specific parts.

Final Words

Modular monoliths are great when you’re starting out or working with a small team. They keep things simple and easier to manage. As your app grows in scale and complexity, microservices offer the flexibility and independence teams need. If you’re at that stage, it may be time to hire .NET developers who can guide the transition and build scalable services.

The post What Are The Differences Between Modular Monolith Vs Microservices in .NET: When To Choose What? appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/modular-monolith-vs-microservices-dotnet/feed/ 0
How Do You Handle Distributed Transactions in .NET Microservices? https://www.cmarix.com/qanda/how-do-you-handle-distributed-transactions-in-net-microservices/ https://www.cmarix.com/qanda/how-do-you-handle-distributed-transactions-in-net-microservices/#respond Wed, 02 Jul 2025 10:11:05 +0000 https://www.cmarix.com/qanda/?p=1589 In a microservices architecture, each service usually owns its own database. This design keeps services independent and scalable. But problems arise when a business operation needs to span across multiple services. For example, placing an order might involve: This kind of workflow creates what’s called a distributed transaction, and managing it consistently is one of […]

The post How Do You Handle Distributed Transactions in .NET Microservices? appeared first on CMARIX QandA.

]]>
In a microservices architecture, each service usually owns its own database. This design keeps services independent and scalable. But problems arise when a business operation needs to span across multiple services.

For example, placing an order might involve:

  • OrderService to create the order
  • InventoryService to reduce stock
  • PaymentService to charge the customer

This kind of workflow creates what’s called a distributed transaction, and managing it consistently is one of the biggest challenges in microservices.

What Is a Distributed Transaction?

A distributed transaction involves multiple operations across different services or databases that need to succeed or fail together. In a traditional system, this might be easy to manage. But in a microservices setup, where data is distributed and services are autonomous, it gets more complicated.

Why Not Use Two-Phase Commit (2PC)?

Two-Phase Commit (2PC) is a classic way to coordinate distributed transactions. It tries to ensure that either all operations succeed or none do. But in microservices, 2PC is rarely used because:

  • It adds significant complexity
  • Many modern tools (like NoSQL databases and message brokers) do not support it
  • It can hurt performance and availability, especially in high-scale systems

So instead of strict consistency, most microservices systems aim for eventual consistency using patterns like Saga and Outbox.

Outbox Pattern: Reliable Event Publishing

The Outbox pattern helps services publish events reliably without losing messages. Here’s how it works:

  1. A service writes to its local database and stores an event in an “outbox” table in the same transaction
  2. A background process or message relay picks up the event and publishes it to a message broker
  3. If the system crashes before the message is sent, the outbox process will retry

Why this works:

  • You avoid partial failures (data saved but message lost)
  • You guarantee that business changes and related events are in sync
  • It’s simple and uses local database transactions only

Saga Pattern: Coordinating Multiple Services

The Saga pattern is used when a business process involves multiple steps across different services. Each step is a local transaction, and if something fails, a compensating action is triggered to undo the change. For example:

  1. PaymentService charges the customer
  2. InventoryService reserves the product
  3. ShippingService starts the delivery

If step 3 fails, the saga can trigger compensations like:

  • Undo the inventory reservation
  • Refund the payment

Sagas can be implemented in two ways:

  • Choreography: Services listen to and react to events from other services
  • Orchestration: A central coordinator service tells others what to do next

Summary

Distributed transactions in microservices are hard to get right. Instead of trying to keep everything tightly consistent, most systems go for eventual consistency using patterns like:

  • Outbox for safe and reliable messaging
  • Saga for coordinating workflows that span multiple services

These approaches reduce complexity, improve scalability, and let services remain independent while still working together effectively.

The post How Do You Handle Distributed Transactions in .NET Microservices? appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/how-do-you-handle-distributed-transactions-in-net-microservices/feed/ 0
What Is an API Gateway and Which One Is Used in .NET? https://www.cmarix.com/qanda/api-gateway-in-net/ https://www.cmarix.com/qanda/api-gateway-in-net/#respond Wed, 02 Jul 2025 10:01:52 +0000 https://www.cmarix.com/qanda/?p=1581 When you’re working with microservices in .NET, you’ll often have multiple services like authentication, user, order, and product. Each one has its own API, and if your client apps try to call these services directly, a few problems can come up: To make things easier and more secure, an API Gateway is often introduced. What […]

The post What Is an API Gateway and Which One Is Used in .NET? appeared first on CMARIX QandA.

]]>
When you’re working with microservices in .NET, you’ll often have multiple services like authentication, user, order, and product. Each one has its own API, and if your client apps try to call these services directly, a few problems can come up:

  • The routing logic gets complicated
  • There are more security risks with multiple public endpoints
  • Common features like logging, rate limiting, or authentication have to be repeated in each service

To make things easier and more secure, an API Gateway is often introduced.

What Is an API Gateway?

An API Gateway is a single entry point for all requests going into your microservices system. It acts like a traffic manager, sitting in front of your services and forwarding client requests to the right one.

But it does more than just routing. An API Gateway can also handle things like:

  • Routing requests to the right service
  • Authenticating and authorizing users
  • Balancing traffic across multiple instances
  • Caching responses to reduce load
  • Limiting how many requests a client can make
  • Combining data from multiple services into one response (response aggregation)

This central point makes it easier to manage and scale your system, while also improving security and reducing duplicated logic across services.

Which API Gateway Tools Are Used in .NET?

There are two popular tools for building an API Gateway in .NET:

1. Ocelot

Ocelot is a lightweight API Gateway designed specifically for .NET applications. It’s easy to set up using a JSON configuration file and works well for small to medium-sized projects.

It supports:

  • Routing
  • Authentication and authorization
  • Rate limiting
  • Logging
  • Aggregating responses from multiple services

2. YARP (Yet Another Reverse Proxy)

YARP is a newer, more flexible reverse proxy built by Microsoft. It runs on ASP.NET Core and is highly customizable. YARP is a great choice if you need more advanced features, dynamic routing, or deeper control over how requests are handled.

It’s especially useful in larger, more complex systems where performance and scalability are key.

Why Use an API Gateway?

Adding an API Gateway to your microservices setup brings several benefits:

  • Clients only need to call one endpoint, which keeps things simple
  • You can apply security and authentication in one place
  • It’s easier to monitor and log traffic centrally
  • You can scale and evolve backend services without breaking the client
  • New features like versioning or response shaping can be added without touching individual services

Conclusion

An API Gateway is an essential part of any well-structured microservices system in .NET. It helps you simplify client interactions, secure your services, and prepare your system for future growth.

If you’re starting with a smaller setup, Ocelot is quick and easy to use. For more flexibility and advanced scenarios, YARP is a powerful choice backed by Microsoft.

Let me know if you’d like help setting one up in your project.

The post What Is an API Gateway and Which One Is Used in .NET? appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/api-gateway-in-net/feed/ 0
How Do Microservices Communication in .NET? https://www.cmarix.com/qanda/how-do-microservices-communication-in-net/ https://www.cmarix.com/qanda/how-do-microservices-communication-in-net/#respond Wed, 02 Jul 2025 09:54:44 +0000 https://www.cmarix.com/qanda/?p=1572 Microservices are designed to be independent, but they still need to interact with each other to fulfill broader business workflows. In .NET, communication between microservices can be synchronous or asynchronous. Choosing the right approach depends on your performance requirements, architecture complexity, and reliability goals. Synchronous Communication Synchronous communication means one service directly calls another and […]

The post How Do Microservices Communication in .NET? appeared first on CMARIX QandA.

]]>
Microservices are designed to be independent, but they still need to interact with each other to fulfill broader business workflows. In .NET, communication between microservices can be synchronous or asynchronous. Choosing the right approach depends on your performance requirements, architecture complexity, and reliability goals.

Synchronous Communication

Synchronous communication means one service directly calls another and waits for a response. This is typically used for immediate, request-response scenarios.

HTTP Communication (REST via HttpClient)

HTTP is the most widely used communication method, particularly suitable for external APIs or simple internal interactions.

Example: Product Service exposing an endpoint

[ApiController]
[Route("api/products")]
public class ProductController : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult GetProduct(int id)
    {
        var product = new Product { Id = id, Name = "Laptop", Price = 999.99 };
        return Ok(product);
    }
}

Register HttpClient in Program.cs

builder.Services.AddHttpClient<IProductClient, ProductClient>(client =>
{
    client.BaseAddress = new Uri("https://localhost:7011/");
});

Client Interface and Implementation

public interface IProductClient
{
    Task<Product> GetProductAsync(int id);
}

public class ProductClient : IProductClient
{
    private readonly HttpClient _httpClient;

    public ProductClient(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<Product> GetProductAsync(int id)
    {
        return await _httpClient.GetFromJsonAsync<Product>($"api/products/{id}")
               ?? throw new Exception("Product not found");
    }
}

Order Service Consuming the Product Service

[ApiController]
[Route("api/orders")]
public class OrderController : ControllerBase
{
    private readonly IProductClient _productClient;

    public OrderController(IProductClient productClient)
    {
        _productClient = productClient;
    }

    [HttpPost]
    public async Task<IActionResult> CreateOrder(int productId)
    {
        var product = await _productClient.GetProductAsync(productId);
        // Logic to create order
        return Ok($"Order placed for {product.Name}");
    }
}

Advantages:

  • Simple and widely supported
  • Easy to debug and monitor

Drawbacks:

  • Can cause tight coupling
  • Latency and error handling need to be managed explicitly

gRPC (for Efficient Binary Communication)

gRPC is a high-performance framework that uses HTTP/2 and Protocol Buffers. It’s a good fit for internal communication where speed and efficiency are important.gRPC Service Definition (product.proto)

syntax = "proto3";

service Product {
  rpc GetProduct (ProductRequest) returns (ProductResponse);
}

message ProductRequest {
  int32 id = 1;
}

message ProductResponse {
  int32 id = 1;
  string name = 2;
  double price = 3;
}

Server-Side Registration

app.MapGrpcService<ProductServiceImpl>();

Client-Side Call

var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new Product.ProductClient(channel);

var reply = await client.GetProductAsync(new ProductRequest { Id = 1 });
Console.WriteLine(reply.Name);

Advantages:

  • High throughput, low latency
  • Contract-first development with strong typing

Drawbacks:

  • More setup required
  • Not as straightforward for public APIs

Conclusion

In .NET microservices, you have two main options for synchronous communication:

  • Use HttpClient (via IHttpClientFactory) for simple REST-based calls.
  • Use gRPC for high-performance internal communication between services.

In many real-world systems, both methods are used together, REST for public-facing endpoints, and gRPC internally where performance is critical. If you’re interested, we can also cover asynchronous messaging patterns using message brokers like RabbitMQ or Azure Service Bus.

The post How Do Microservices Communication in .NET? appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/how-do-microservices-communication-in-net/feed/ 0
What are Some Best Practices for .NET Microservices? https://www.cmarix.com/qanda/what-are-the-best-practices-for-net-microservices/ https://www.cmarix.com/qanda/what-are-the-best-practices-for-net-microservices/#respond Wed, 02 Jul 2025 09:19:01 +0000 https://www.cmarix.com/qanda/?p=1562 Microservices in .NET allow you to build scalable, independent, and deployable services that communicate via APIs or messaging systems. However, microservices come with complexity, especially around communication, deployment, monitoring, and consistency. Single Responsibility Principle API Contracts and Versioning Use API versioning to avoid breaking clients. Secure Each Service Use JWT Bearer tokens with ASP.NET Core. […]

The post What are Some Best Practices for .NET Microservices? appeared first on CMARIX QandA.

]]>
Microservices in .NET allow you to build scalable, independent, and deployable services that communicate via APIs or messaging systems. However, microservices come with complexity, especially around communication, deployment, monitoring, and consistency.

Single Responsibility Principle

// BlogService
GET /api/posts
POST /api/posts

// UserService (separate microservice)
GET /api/users
POST /api/users/register

API Contracts and Versioning

Use API versioning to avoid breaking clients.

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/posts")]
public class PostsController : ControllerBase
{
    [HttpGet]
    public IActionResult GetPosts() => Ok(...);
}

Secure Each Service

Use JWT Bearer tokens with ASP.NET Core.

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = "https://auth.example.com";
        options.Audience = "blog-api";
    });

Conclusion

Designing microservices in .NET is more than just splitting projects, it’s about clear boundaries, robust communication, strong observability, and automation. By following these practices, you can build resilient, scalable, and maintainable systems.

The post What are Some Best Practices for .NET Microservices? appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/what-are-the-best-practices-for-net-microservices/feed/ 0
How Do You Implement Dynamic Component Rendering in Blazor? https://www.cmarix.com/qanda/dynamic-component-rendering-in-blazor/ https://www.cmarix.com/qanda/dynamic-component-rendering-in-blazor/#respond Fri, 27 Jun 2025 13:51:30 +0000 https://www.cmarix.com/qanda/?p=1554 Blazor allows developers to build rich, interactive web UIs with reusable components. But what happens when you need to render components based on user actions, backend data, or a CMS layout? That’s where dynamic component rendering comes in a powerful feature that lets you render components at runtime without directly referencing them in your Razor […]

The post How Do You Implement Dynamic Component Rendering in Blazor? appeared first on CMARIX QandA.

]]>
Blazor allows developers to build rich, interactive web UIs with reusable components. But what happens when you need to render components based on user actions, backend data, or a CMS layout? That’s where dynamic component rendering comes in a powerful feature that lets you render components at runtime without directly referencing them in your Razor markup.

What Is Dynamic Component Rendering?

Dynamic component rendering means you can display a component in your UI by specifying its type and parameters programmatically. Instead of writing static Razor code, you tell Blazor what component to load, along with any data it needs, and Blazor takes care of rendering it on the fly.

This is especially useful when the structure of your UI isn’t fully known until the app is running. For example, a blog platform might use this technique to render different types of content blocks (text, image, video) based on data from a backend system.

How It Works Behind the Scenes

Blazor provides a built-in component that enables dynamic rendering. You specify the component type you want to render and pass any required parameters using a key-value structure. Blazor then instantiates and displays that component at runtime.

This approach is often used in:

  • CMS-style applications where page layouts and content blocks are stored in a database
  • Plugin systems or dashboards where users can add, remove, or rearrange widgets
  • Admin panels where components change based on user roles or settings

Benefits of Dynamic Rendering

  • Flexible UI Composition: Load different components based on user actions, roles, or data structures.
  • Supports CMS Architectures: Ideal for content-driven systems where page layout is defined outside the app.
  • Clean and Maintainable Code:  Avoid hardcoding every UI variation by handling it through runtime logic.
  • Future-Proof UI Logic: Add or swap components without touching Razor markup — making your app more modular and scalable.

Conclusion

Rendering components dynamically in Blazor is a total game-changer. It gives your app the flexibility to change layouts, content, or even entire features on the fly all without hardcoding everything. Whether you’re building a CMS, a dashboard, or a plugin system, this approach makes your life easier and your app more future-proof. It’s all about working smarter, not harder.

The post How Do You Implement Dynamic Component Rendering in Blazor? appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/dynamic-component-rendering-in-blazor/feed/ 0
How Do You Inject Services into a Custom HttpClient in Blazor? https://www.cmarix.com/qanda/how-to-inject-services-in-blazor-custom-httpclients/ https://www.cmarix.com/qanda/how-to-inject-services-in-blazor-custom-httpclients/#respond Fri, 27 Jun 2025 13:03:54 +0000 https://www.cmarix.com/qanda/?p=1549 Injecting services into a custom HttpClient is a common practice in Blazor applications, especially when dealing with secure API calls, logging, or request customization. For example, in a blog platform, API requests might need authentication tokens, custom headers, or logging—all of which can be managed through a custom HttpClient service. Why Inject Services into a […]

The post How Do You Inject Services into a Custom HttpClient in Blazor? appeared first on CMARIX QandA.

]]>
Injecting services into a custom HttpClient is a common practice in Blazor applications, especially when dealing with secure API calls, logging, or request customization. For example, in a blog platform, API requests might need authentication tokens, custom headers, or logging—all of which can be managed through a custom HttpClient service.

Why Inject Services into a Custom HttpClient?

In real-world Blazor apps, API calls often need to:

  • Include a JWT or session token for authentication
  • Log outgoing requests or responses
  • Set custom headers like X-Blog-App
  • Handle retry logic or transient faults

To achieve this cleanly, you can wrap HttpClient inside a custom service and inject any needed dependencies, like a token provider or logger.

How to Inject Services in Blazor Custom HttpClients?

Step 1: Create a BlogApiClient Service

using System.Net.Http.Headers;
using System.Net.Http.Json;
using BlogExample.Models;

public class BlogApiClient
{
    private readonly HttpClient _httpClient;
    private readonly ITokenService _tokenService;

    public BlogApiClient(HttpClient httpClient, ITokenService tokenService)
    {
        _httpClient = httpClient;
        _tokenService = tokenService;
    }

    public async Task<List<BlogPost>> GetAllPostsAsync()
    {
        var token = await _tokenService.GetTokenAsync();
        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        return await _httpClient.GetFromJsonAsync<List<BlogPost>>("api/blogposts");
    }

    public async Task<HttpResponseMessage> CreatePostAsync(BlogPost post)
    {
        var token = await _tokenService.GetTokenAsync();
        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        return await _httpClient.PostAsJsonAsync("api/blogposts", post);
    }
}

Step 2: Create a Token Service

public interface ITokenService
{
    Task<string> GetTokenAsync();
}

public class FakeTokenService : ITokenService
{
    public Task<string> GetTokenAsync()
    {
        // Simulated token, replace with real implementation
        return Task.FromResult("your-fake-jwt-token-here");
    }
}

Step 3: Register Services in Program.cs

builder.Services.AddScoped<ITokenService, FakeTokenService>();

builder.Services.AddHttpClient<BlogApiClient>(client =>
{
    client.BaseAddress = new Uri("https://your-api-base-url.com/");
});

Step 4: Use BlogApiClient in a Razor Component

@inject BlogApiClient ApiClient

<h3>All Blog Posts</h3>

@if (posts == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <ul class="list-group">
        @foreach (var post in posts)
        {
            <li class="list-group-item">
                <strong>@post.Title</strong><br />
                @post.Content.Substring(0, Math.Min(post.Content.Length, 100))...
            </li>
        }
    </ul>
}

@code {
    private List<BlogPost> posts;

    protected override async Task OnInitializedAsync()
    {
        posts = await ApiClient.GetAllPostsAsync();
    }
}

Conclusion

By creating a custom HttpClient wrapper and injecting services like a token provider, you can build cleaner, more testable Blazor components. This approach also keeps your API logic centralized and consistent across the app. Whether you’re building a blog platform or an enterprise dashboard, this pattern scales well for real-world use cases.

The post How Do You Inject Services into a Custom HttpClient in Blazor? appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/how-to-inject-services-in-blazor-custom-httpclients/feed/ 0
What’s the Difference Between IJSRuntime and IJSInProcessRuntime? https://www.cmarix.com/qanda/difference-between-ijsruntime-and-ijsinprocessruntime/ https://www.cmarix.com/qanda/difference-between-ijsruntime-and-ijsinprocessruntime/#respond Fri, 27 Jun 2025 12:56:38 +0000 https://www.cmarix.com/qanda/?p=1541 In Blazor, JavaScript Interop allows C# code to call JavaScript functions and vice versa. This is essential when interacting with browser APIs, accessing localStorage, manipulating the DOM, or working with third-party JS libraries. Blazor provides two main interfaces for this purpose: IJSRuntime and IJSInProcessRuntime. IJSRuntime – Asynchronous Interop This is the standard way to call […]

The post What’s the Difference Between IJSRuntime and IJSInProcessRuntime? appeared first on CMARIX QandA.

]]>
In Blazor, JavaScript Interop allows C# code to call JavaScript functions and vice versa. This is essential when interacting with browser APIs, accessing localStorage, manipulating the DOM, or working with third-party JS libraries. Blazor provides two main interfaces for this purpose: IJSRuntime and IJSInProcessRuntime.

IJSRuntime – Asynchronous Interop

This is the standard way to call JavaScript from C# in both Blazor Server and Blazor WebAssembly. It uses asynchronous calls to avoid blocking the UI thread.

When to Use:

  • The app runs on Blazor Server or needs cross-platform compatibility.
  • You are calling long-running or async JavaScript functions.

UI responsiveness is a priority.

@inject IJSRuntime JS

<button @onclick="SaveToLocalStorage">Save</button>
<button @onclick="ReadFromLocalStorage">Read</button>

@code {
    async Task SaveToLocalStorage()
    {
        await JS.InvokeVoidAsync("localStorage.setItem", "title", "Blazor Blog");
    }

    async Task ReadFromLocalStorage()
    {
        string value = await JS.InvokeAsync<string>("localStorage.getItem", "title");
        Console.WriteLine($"Value from localStorage: {value}");
    }
}

IJSInProcessRuntime – Synchronous Interop

This is a more specialized interface for Blazor WebAssembly only. It allows synchronous calls to JavaScript, which can reduce latency in performance-critical scenarios.

When to Use:

  • The app runs only on Blazor WebAssembly.
  • You need fast, synchronous access to JS (e.g., reading small values).
  • The JS function is quick and doesn’t block the UI thread.
@inject IJSRuntime JSRuntime

<button @onclick="ReadSync">Read Sync</button>

@code {
    void ReadSync()
    {
        if (JSRuntime is IJSInProcessRuntime jsInProcess)
        {
            string title = jsInProcess.Invoke<string>("localStorage.getItem", "title");
            Console.WriteLine($"(Sync) Value: {title}");
        }
    }
}

What are the Key Differences IJSRuntime vs IJSInProcessRuntime?

FeatureIJSRuntime (Async)IJSInProcessRuntime (Sync)
Available InBlazor Server & WebAssemblyBlazor WebAssembly only
Call TypeAsynchronousSynchronous
Thread SafetyNon-blocking, UI-safeCan block UI if misused
Usage RecommendationPreferred for most scenariosUse only for small, fast calls

Conclusion

Use IJSRuntime for safe, asynchronous JS interop across both hosting models. Only use IJSInProcessRuntime in Blazor WebAssembly when you need fast synchronous access for lightweight operations. Avoid blocking the UI thread and always consider portability and performance when choosing between the two.

The post What’s the Difference Between IJSRuntime and IJSInProcessRuntime? appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/difference-between-ijsruntime-and-ijsinprocessruntime/feed/ 0