LESSON 7 OF 20

7. Service-to-Service HTTP Communication with Service Discovery

Learn how the Order service communicates with Catalog and Inventory through Aspire service discovery, HttpClientFactory, and typed clients without hard-coded URLs.

50 dk 29

Introduction

In the previous lesson, we defined resources and references in the Aspire AppHost. In this lesson, we will see how those references become usable application configuration. Our goal is to let the Order service call the Catalog and Inventory services over HTTP without using hard-coded addresses such as http://localhost:5001 or http://localhost:5002.

Ports, host names, and network locations can change in distributed applications. A service may run on a localhost port during development, on a container network in a local environment, and behind a completely different DNS address in the cloud. Aspire service discovery allows applications to communicate through logical service names instead of knowing the actual network address.

In this lesson, we will implement HttpClientFactory, typed clients, service-name-based endpoint configuration, error handling, and AppHost references as one consistent workflow.

How service discovery works

Aspire service-to-service communication has two connected parts. The first part is declaring a relationship between resources in the AppHost. The second part is configuring an HTTP client in the calling service with a logical endpoint name.

  1. The AppHost creates the catalog and inventory resources.
  2. The Order resource references those services with WithReference.
  3. Aspire provides the corresponding endpoint information to the Order service through configuration.
  4. The Order code uses logical addresses such as https+http://catalog and https+http://inventory.
  5. The service discovery resolver translates those names into actual endpoints at runtime.

The important detail is that catalog must match the resource name in the AppHost. It is not merely a URL fragment; it is the logical identity of the service in the application topology.

Defining service references in the AppHost

Assuming the resources have already been created, the AppHost can look like this:

var builder = DistributedApplication.CreateBuilder(args);

var catalog = builder.AddProject<Projects.Catalog>("catalog");
var inventory = builder.AddProject<Projects.Inventory>("inventory");

builder.AddProject<Projects.Order>("order")
    .WithReference(catalog)
    .WithReference(inventory);

builder.Build().Run();

WithReference(catalog) allows the Order service to receive Catalog endpoint information. The Inventory reference does the same for Inventory. Without these lines, using catalog or inventory in the Order client may result in an unresolved endpoint.

Practical rule: For one service to call another, the AppHost must define the reference and the calling application must use an HTTP client configured for service discovery.

Checking the ServiceDefaults integration

Verify that the Order, Catalog, and Inventory projects reference the ServiceDefaults project and call AddServiceDefaults during startup:

var builder = WebApplication.CreateBuilder(args);

builder.AddServiceDefaults();
builder.Services.AddControllers();

var app = builder.Build();

app.MapDefaultEndpoints();
app.MapControllers();

app.Run();

AddServiceDefaults enables shared configuration supplied by the template. This includes service discovery, service-discovery support for HTTP clients, standard resilience behavior, health checks, and OpenTelemetry configuration. If this call is missing, typed clients may be registered but logical service names may not resolve as expected.

Creating typed clients

Instead of placing remote HTTP calls directly in a controller, create one typed client for each remote service. Start with a Catalog client:

public sealed record CatalogProduct(
    Guid Id,
    string Sku,
    string Name,
    decimal Price);

public sealed class CatalogClient(HttpClient httpClient)
{
    public async Task<CatalogProduct?> GetProductAsync(
        Guid productId,
        CancellationToken cancellationToken = default)
    {
        using var response = await httpClient.GetAsync(
            $"api/products/{productId}",
            cancellationToken);

        if (response.StatusCode == HttpStatusCode.NotFound)
        {
            return null;
        }

        response.EnsureSuccessStatusCode();

        return await response.Content.ReadFromJsonAsync<CatalogProduct>(
            cancellationToken);
    }
}

The HttpClient received by the constructor is created by the framework. The client contains no host name or port. It only uses the relative path exposed by the Catalog API.

Create a similar client for Inventory:

public sealed record StockResult(
    Guid ProductId,
    int AvailableQuantity);

public sealed class InventoryClient(HttpClient httpClient)
{
    public async Task<StockResult?> GetStockAsync(
        Guid productId,
        CancellationToken cancellationToken = default)
    {
        using var response = await httpClient.GetAsync(
            $"api/inventory/{productId}",
            cancellationToken);

        if (response.StatusCode == HttpStatusCode.NotFound)
        {
            return null;
        }

        response.EnsureSuccessStatusCode();

        return await response.Content.ReadFromJsonAsync<StockResult>(
            cancellationToken);
    }
}

Sharing every DTO through a common library is not always necessary. To preserve data ownership, it is often safer for Order to define small response models for the data it actually needs within its own service boundary.

Configuring service-name-based endpoints with HttpClientFactory

Register the typed clients in the dependency injection container and use service names as their base addresses:

builder.Services.AddHttpClient<CatalogClient>(client =>
{
    client.BaseAddress = new Uri("https+http://catalog");
});

builder.Services.AddHttpClient<InventoryClient>(client =>
{
    client.BaseAddress = new Uri("https+http://inventory");
});

The https+http scheme used by Aspire's endpoint resolution approach prefers the HTTPS endpoint and allows fallback to HTTP. The exact endpoint scheme and security policy can vary according to the project configuration. With the standard service defaults, service discovery is added to the HTTP client pipeline.

This configuration allows the same code to run in different environments. Locally, catalog may resolve to a localhost port; on a container network, it may resolve to the service's network endpoint. The Order code does not need to know which one is being used.

Using both services in the Order workflow

Before creating an order, check that the product exists in Catalog and that sufficient stock is available in Inventory:

public sealed record CreateOrderRequest(
    Guid ProductId,
    int Quantity);

public sealed record OrderCheckResult(
    bool Accepted,
    string? Reason);

public sealed class OrderWorkflow(
    CatalogClient catalogClient,
    InventoryClient inventoryClient)
{
    public async Task<OrderCheckResult> ValidateAsync(
        CreateOrderRequest request,
        CancellationToken cancellationToken = default)
    {
        var product = await catalogClient.GetProductAsync(
            request.ProductId,
            cancellationToken);

        if (product is null)
        {
            return new(false, "Product was not found.");
        }

        var stock = await inventoryClient.GetStockAsync(
            request.ProductId,
            cancellationToken);

        if (stock is null || stock.AvailableQuantity < request.Quantity)
        {
            return new(false, "Insufficient stock is available.");
        }

        return new(true, null);
    }
}

This class separates remote calls from the controller. The controller only receives the request, invokes the workflow, and converts the result into an HTTP response.

[ApiController]
[Route("api/orders")]
public sealed class OrdersController(OrderWorkflow workflow) : ControllerBase
{
    [HttpPost("validate")]
    public async Task<IActionResult> Validate(
        CreateOrderRequest request,
        CancellationToken cancellationToken)
    {
        var result = await workflow.ValidateAsync(
            request,
            cancellationToken);

        return result.Accepted
            ? Ok(result)
            : BadRequest(result);
    }
}

Parallel calls and dependency order

If the Catalog response is not required to make the Inventory request, the two calls can be started in parallel to reduce latency:

var productTask = catalogClient.GetProductAsync(
    request.ProductId,
    cancellationToken);

var stockTask = inventoryClient.GetStockAsync(
    request.ProductId,
    cancellationToken);

await Task.WhenAll(productTask, stockTask);

var product = await productTask;
var stock = await stockTask;

Parallelism is not always the right choice. If one call depends on the output of another, keep the calls sequential. Also design logging and error reporting carefully when two remote calls can fail at the same time.

Error handling and observability

Remote calls require more than checking for HTTP 200. At minimum, distinguish the following cases:

  • 404: The resource was not found; depending on the workflow, this may be an expected result.
  • 400: The request data may be invalid and usually should not be retried.
  • 5xx: The remote service or infrastructure may have a problem, so resilience policies may apply.
  • Timeout: The service may be unavailable or slow; return a controlled error to the caller.

The HTTP resilience configuration provided by ServiceDefaults can provide behaviors such as retries. However, retries are not safe for every operation. Do not enable automatic retries for side-effecting POST operations such as order creation without considering idempotency. The GET requests in this lesson are read-only and are more suitable for retry scenarios.

HTTP calls made through service discovery can be observed through OpenTelemetry HTTP instrumentation. In the Aspire Dashboard, inspect the trace spans from Order to Catalog and Inventory. This makes it easier to identify which service contributed to total latency and which remote call failed.

Common mistakes

  • Omitting WithReference in the AppHost: The resolver cannot find the service endpoint. Add Catalog and Inventory references to the Order resource.
  • Using the wrong service name: The catalog name in the AppHost and in the client must match. catalog-api and catalog are different names.
  • Using a hard-coded localhost address: This fails when ports or container networking change.
  • Skipping AddServiceDefaults: Service discovery and HTTP pipeline configuration may be incomplete.
  • Combining BaseAddress and paths incorrectly: Keep BaseAddress and relative endpoint paths consistent, usually without a trailing slash in the BaseAddress.
  • Converting every HTTP error into 500: Handle 404, timeout, and 503 according to their business meaning.
  • Sharing every DTO between services: This can create tight coupling. Share only contracts that are genuinely common and stable.

Short practice exercise

Complete the following exercise to reinforce the concepts from this lesson:

  1. Add WithReference for Catalog and Inventory to the Order resource in the AppHost.
  2. Verify that the Order project calls ServiceDefaults during startup.
  3. Create the CatalogClient and InventoryClient typed client classes.
  4. Register them with https+http://catalog and https+http://inventory.
  5. Return product details and stock information together from one endpoint.
  6. Inspect the related logs and trace records in the Aspire Dashboard.
  7. Stop the Catalog resource and observe the error returned by the Order call.

Success criterion: The code must contain no port numbers or localhost addresses. The Order service should reach Catalog and Inventory only through their logical service names.

Conclusion

In this lesson, we enabled the Order service to communicate with Catalog and Inventory through Aspire service discovery. We defined topology connections with WithReference in the AppHost, enabled discovery through ServiceDefaults, and created typed clients with HttpClientFactory.

This approach separates service addresses from application code, hides endpoint differences between local and distributed environments, and moves HTTP communication into testable classes. In the next stage, we will add more advanced resilience, timeout, fallback, and error-contract strategies to make distributed communication more reliable.

Sources