2m.Shared.Infrastructure 1.2.1

dotnet add package 2m.Shared.Infrastructure --version 1.2.1
                    
NuGet\Install-Package 2m.Shared.Infrastructure -Version 1.2.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="2m.Shared.Infrastructure" Version="1.2.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="2m.Shared.Infrastructure" Version="1.2.1" />
                    
Directory.Packages.props
<PackageReference Include="2m.Shared.Infrastructure" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add 2m.Shared.Infrastructure --version 1.2.1
                    
#r "nuget: 2m.Shared.Infrastructure, 1.2.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package 2m.Shared.Infrastructure@1.2.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=2m.Shared.Infrastructure&version=1.2.1
                    
Install as a Cake Addin
#tool nuget:?package=2m.Shared.Infrastructure&version=1.2.1
                    
Install as a Cake Tool

Shared Infrastructure Library

This library provides reusable components for ASP.NET Core applications, including authentication, context services, middleware, health checks, HTTP resilience, and more.

Table of Contents

  1. Installation
  2. Authentication & User Context
  3. Time Zone Handling
  4. Swagger Configuration
  5. MassTransit/RabbitMQ Integration
  6. Health Checks
  7. Resilient HTTP Client
  8. Pagination Helper
  9. Middleware Setup

Installation

  1. Add the shared infrastructure project to your solution
  2. Reference the project in your API application
  3. Register services in your application startup:
    • Call AddSharedInfrastructure() on your service collection
  4. Configure the middleware pipeline:
    • Use UseSharedInfrastructure() for standard components
    • Add UseSharedHealthChecks() for health endpoints

Authentication & User Context

Configuration

Add JWT settings to your application configuration:

  • Key: 256-bit secret key for signing tokens
  • Issuer: Token issuer identifier
  • Audience: Valid token audience
  "Jwt": {
    "Key": "YOUR-256-BIT-SECRET-KEY",
    "Issuer": "yourdomain.com",
    "Audience": "yourdomain.com",
    "ExpireMinutes": 60
  },

User Context Usage

The IUserContext service provides access to:

  • Current user's unique identifier
  • Associated company and branch identifiers
  • Role verification methods
  • Claims-based information from authenticated tokens

Inject IUserContext into services to access authenticated user information throughout your application.

private readonly IUserContext _user;
_user.UserId

Time Zone Handling

Middleware Setup

Add time zone middleware to automatically handle client time zones:

  • Processes "TimeZone" claim from authentication tokens
  • Falls back to UTC for invalid or missing time zones
  • Stores resolved time zone in request context

Service Usage

Inject ITimeZoneContext into services to:

  • Convert UTC times to user's local time
  • Convert local times back to UTC
  • Perform time-sensitive operations in the correct time zone
 private readonly ITimeZoneContext _tz;
 _tz.ToUtc(Date);
 _tz.ToUserTime(Date);

Swagger Configuration

Automatically configures Swagger with JWT support when using the shared infrastructure setup.

Customization Options

  • Set custom API title
  • Define API version number
  • Modify security scheme details
  • Adjust authentication requirements
configureSwagger: options =>
{
    options.Title = "IdentityService API";
    options.Version = "v1";
}

Access

  • Development environment: Access at /swagger endpoint
  • Production: Secure through authentication and authorization

MassTransit/RabbitMQ Integration

Setup

Configure messaging through options:

  • Specify RabbitMQ host address
  • Provide connection credentials
  • Register message consumers
  • Configure endpoint mappings
configureMassTransit: options =>
{
    options.Host = "rabbitmq";
    options.Username = "guest";
    options.Password = "guest";
}

Implementation

Create message consumers to handle specific message types. The library manages:

  • Connection pooling and reconnection
  • Message serialization
  • Error handling
  • Endpoint configuration

Health Checks

Setup

  1. Register health checks with AddSharedHealthChecks()
  2. Enable health endpoint with UseSharedHealthChecks()
  3. Configure database connection strings in application settings

Features

  • PostgreSQL database connectivity check
  • RabbitMQ service availability verification
  • Configurable component inclusion/exclusion
  • Standardized health endpoint at /health
  • Detailed status reporting

Resilient HTTP Client

Registration

Configure resilient HTTP clients with:

  • Base address from configuration
  • Connection pooling with automatic renewal
  • Automatic retry for transient socket errors
  • Configurable timeout periods
  • Exponential backoff strategy for retries

Usage

Define typed clients that leverage the resilient handler. The library automatically handles:

  • Transient network errors
  • DNS resolution failures
  • Temporary connection issues
  • Socket exceptions
builder.Services.AddResilientHttpClient<MetaDataClient>(
    "Services:metadataservice",
    maxRetries: 5,
    timeoutSeconds: 30);

and in appsettings.json

  "Services": {
    "metadataservice": "http://metadataservice"
  },

RefitOrchestrator - HTTP Client Orchestration Library

A robust solution for managing HTTP requests across microservices with Refit and HttpClientFactory.

Features

Type-safe API contracts with Refit
Centralized request handling
Automatic header propagation
Custom request/response modification
Built-in resilience patterns
Comprehensive logging
DI-friendly design

Installation

1. Reference the Shared Library

Add the shared infrastructure project to your solution.

2. Register Services

builder.Services.AddRefitOrchestrator();

public async Task ProcessPayment(PaymentRequest request)
{
    var result = await _orchestrator.ExecuteAsync<IPaymentApi, PaymentResult>(
        client => client.CreatePayment(request),
        clientName: "PaymentClient", // Matches registered HttpClient name
        headers: h => 
        {
            h.Add("X-Idempotency-Key", Guid.NewGuid().ToString());
            h.Add("X-User-Id", "12345");
        },
        requestModifier: req => 
        {
            // Add custom headers or modify request
            req.Headers.Add("Custom-Header", "value");
        });
}

Pagination Helper

Usage

Apply consistent pagination to any queryable data source:

  • Automatic total record count calculation
  • Configurable page sizes
  • Efficient data retrieval
  • Standardized response structure
_db.Permissions.ToPagedResultAsync(page:1, pageSize:10)

Response Format

  • TotalCount: Total records available
  • Page: Current page number
  • PageSize: Number of items per page
  • Data: Collection of paginated results

Logget Adapter

 private readonly ILoggerAdapter<AccountsController> _logger;
 _logger.LogInformation("User {UserId} accessed account details", _user.UserId);

Middleware Setup

Standard Pipeline

Call UseSharedInfrastructure() to enable:

  • Time zone handling
  • Authentication
  • Authorization
  • Swagger documentation UI
  • Health check endpoints

Customization Options

Build custom pipelines by selectively adding components:

  1. TimeZoneMiddleware
  2. Authentication
  3. Authorization
  4. Swagger documentation
  5. Health checks
  6. Custom middleware components

Health Checks Endpoint

  • Path: /health
  • Aggregates all registered health checks
  • Provides machine-readable status report
  • Includes detailed component health information

to add later to the documentation

public void ConfigureServices(IServiceCollection services)
{
    services.AddPostgresDbContext<MyAppDbContext>(Configuration, "DefaultConnection");

    // Other service registrations
}

public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
{
    serviceProvider.ApplyMigrations<MyAppDbContext>();

    // Other app configuration
}

##TODO add sirelog to garafana

Support

For implementation assistance, contact: platform-engineering@yourcompany.com
Issue tracking: GitHub Issues
Documentation: Shared Infrastructure Wiki

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.2.1 140 6/18/2025
1.2.0 133 6/17/2025
1.1.9 138 6/17/2025
1.1.8 140 6/17/2025
1.1.6 139 6/17/2025
1.1.5 138 6/16/2025
1.1.4 135 6/16/2025
1.1.3 133 6/16/2025
1.1.2 157 6/16/2025
1.1.1 137 6/15/2025
1.1.0 108 6/15/2025
1.0.9 112 6/15/2025
1.0.8 105 6/15/2025
1.0.7 103 6/15/2025
1.0.6 114 6/15/2025
1.0.5 121 6/15/2025
1.0.4 132 6/15/2025
1.0.3 124 6/15/2025
1.0.2 123 6/15/2025
1.0.1 125 6/15/2025
1.0.0 128 6/15/2025