Skip to content

Class ServiceDefaultsExtensions

Namespace: Momentum.ServiceDefaults
Assembly: Momentum.ServiceDefaults.dll

Provides extension methods for configuring service defaults in the application.

csharp
public static class ServiceDefaultsExtensions

Inheritance

objectServiceDefaultsExtensions

Inherited Members

object.GetType(), object.MemberwiseClone(), object.ToString(), object.Equals(object?), object.Equals(object?, object?), object.ReferenceEquals(object?, object?), object.GetHashCode()

Properties

EntryAssembly

Gets or sets the entry assembly for the application.

csharp
public static Assembly EntryAssembly { get; set; }

Property Value

Assembly

Exceptions

InvalidOperationException

Thrown when attempting to get the entry assembly, and it cannot be determined.

Methods

AddServiceDefaults(WebApplicationBuilder)

Adds common service defaults to the application builder for production-ready microservices.

csharp
public static IHostApplicationBuilder AddServiceDefaults(this WebApplicationBuilder builder)

Parameters

builder WebApplicationBuilder

The web application builder to configure.

Returns

IHostApplicationBuilder

The configured host application builder for method chaining.

Examples

Basic E-commerce API Setup

csharp
var builder = WebApplication.CreateBuilder(args);

// Configure core service infrastructure
builder.AddServiceDefaults();

// Add your business services
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddDbContext<EcommerceDbContext>();

var app = builder.Build();

// Map health check endpoints
app.MapDefaultHealthCheckEndpoints();

// Map your API endpoints
app.MapGroup("/api/orders").MapOrdersApi();

// Run with proper initialization and error handling
await app.RunAsync(args);

Configuration in appsettings.json

json
{
  "ConnectionStrings": {
    "ServiceBus": "Host=localhost;Database=ecommerce_messaging;Username=app;Password=secret"
  },
  "OpenTelemetry": {
    "ActivitySourceName": "ECommerceAPI",
    "MessagingMeterName": "ECommerce.Messaging"
  },
  "ServiceBus": {
    "Domain": "ECommerce",
    "PublicServiceName": "orders-api"
  }
}

Domain Assembly Registration

csharp
// In AssemblyInfo.cs or GlobalUsings.cs
[assembly: DomainAssembly(typeof(Order), typeof(Customer), typeof(Product))]

// This enables automatic discovery of:
// - Command/Query handlers in the Order, Customer, Product assemblies
// - FluentValidation validators
// - Integration events

Domain Assembly Configuration

csharp
// In your API project's GlobalUsings.cs or AssemblyInfo.cs
[assembly: DomainAssembly(typeof(Order), typeof(Customer))]

// This will scan Order and Customer assemblies for validators like:
// Orders.Domain.Commands.CreateOrderValidator
// Customers.Domain.Queries.GetCustomerValidator

Example Validator in Domain Assembly

csharp
// In Orders.Domain assembly
public class CreateOrderValidator : AbstractValidator<CreateOrder>
{
    public CreateOrderValidator()
    {
        RuleFor(x => x.CustomerId)
            .NotEmpty()
            .WithMessage("Customer ID is required");
            
        RuleFor(x => x.Items)
            .NotEmpty()
            .WithMessage("Order must contain at least one item");
            
        RuleForEach(x => x.Items)
            .SetValidator(new OrderItemValidator());
    }
}

Automatic Integration with Wolverine

csharp
// Validation happens automatically in message handlers
public static async Task<OrderCreated> Handle(
    CreateOrder command,  // Automatically validated
    IOrderRepository orders,
    ILogger logger)
{
    // Command is guaranteed to be valid when this executes
    // ValidationException is thrown automatically if invalid
    
    var order = new Order(command.CustomerId, command.Items);
    await orders.SaveAsync(order);
    
    return new OrderCreated(order.Id, order.CustomerId);
}

Standard Application Startup

csharp
var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();

var app = builder.Build();
app.MapDefaultHealthCheckEndpoints();
app.MapOrdersApi();

// This handles both normal execution and CLI commands
await app.RunAsync(args);

Database Migration in Docker

dockerfile
# Dockerfile for migration container
FROM mcr.microsoft.com/dotnet/aspnet:9.0
COPY publish/ /app
WORKDIR /app
ENTRYPOINT ["dotnet", "OrderService.dll", "db-apply"]

Health Check Validation

bash
# In CI/CD pipeline or health monitoring
docker run --rm order-service:latest check-env

# Returns exit code 0 if healthy, non-zero if issues detected

Remarks

Service Defaults Detailed Configuration Guide

Overview

This method configures essential infrastructure for microservices including:

  • HTTPS configuration for Kestrel with secure communication
  • Structured logging with Serilog and OpenTelemetry integration
  • Distributed tracing and metrics collection via OpenTelemetry
  • Wolverine messaging framework with PostgreSQL persistence
  • FluentValidation validators discovery from domain assemblies
  • Health checks with multiple endpoints for liveness/readiness probes
  • Service discovery for container orchestration environments
  • HTTP client resilience with circuit breakers and retry policies

This method is designed to be the single entry point for configuring a production-ready service with observability, resilience, and messaging capabilities required for cloud-native microservices architectures.

Configuration Features

Infrastructure Components

  • HTTPS and Security: Automatic HTTPS configuration with proper certificate handling
  • Logging: Structured logging with Serilog, including request correlation and performance tracking
  • Observability: OpenTelemetry integration for metrics, traces, and distributed monitoring
  • Messaging: Wolverine framework with PostgreSQL for reliable message processing
  • Validation: Automatic discovery and registration of FluentValidation validators
  • Health Checks: Comprehensive health monitoring for infrastructure dependencies
  • Resilience: HTTP client policies with circuit breakers, retries, and timeouts

Production Readiness

The service defaults are designed for production deployment with:

  • Container orchestration compatibility (Kubernetes, Docker Swarm)
  • Cloud-native patterns and best practices
  • Automatic service discovery and registration
  • Performance monitoring and alerting capabilities
  • Fault tolerance and graceful degradation
  • Security headers and HTTPS enforcement

Usage Patterns

Basic Setup

The AddServiceDefaults() method provides a one-line configuration for most microservice scenarios, reducing boilerplate code while ensuring production-grade infrastructure.

Advanced Configuration

For specific business requirements, the method can be combined with additional configuration for custom messaging routes, specialized health checks, or domain-specific observability.

AddValidators(WebApplicationBuilder)

Adds FluentValidation validators from the entry assembly and all domain assemblies.

csharp
public static void AddValidators(this WebApplicationBuilder builder)

Parameters

builder WebApplicationBuilder

The web application builder to configure.

Examples

See for examples.

Remarks

This method automatically discovers and registers FluentValidation validators from:

  • The entry assembly (your main application assembly)
  • All assemblies marked with
Validators are registered as scoped services and integrated with Wolverine's message handling pipeline for automatic validation of commands and queries.

This approach supports the Domain-Driven Design pattern where validation rules are defined close to the domain entities and business logic.

RunAsync(WebApplication, string[])

Runs the web application with proper initialization, error handling, and command-line tool support.

csharp
public static Task RunAsync(this WebApplication app, string[] args)

Parameters

app WebApplication

The web application to run.

args string[]

Command line arguments passed to the application.

Returns

Task

A task that represents the asynchronous operation.

Examples

See for examples.

Remarks

This method provides robust application lifecycle management including:

  • Bootstrap logger initialization for early-stage logging
  • Wolverine CLI command detection and execution for DevOps tasks
  • Graceful exception handling with structured logging
  • Proper log flushing on application shutdown
  • Support for containerized environments and orchestrators

Supported Wolverine Commands:

check-envValidates messaging infrastructure connectivity
codegenGenerates Wolverine handler code for optimization
db-apply, db-assertDatabase schema migration and validation
storageMessage persistence storage management