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
<PackageReference Include="2m.Shared.Infrastructure" Version="1.2.1" />
<PackageVersion Include="2m.Shared.Infrastructure" Version="1.2.1" />
<PackageReference Include="2m.Shared.Infrastructure" />
paket add 2m.Shared.Infrastructure --version 1.2.1
#r "nuget: 2m.Shared.Infrastructure, 1.2.1"
#:package 2m.Shared.Infrastructure@1.2.1
#addin nuget:?package=2m.Shared.Infrastructure&version=1.2.1
#tool nuget:?package=2m.Shared.Infrastructure&version=1.2.1
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
- Installation
- Authentication & User Context
- Time Zone Handling
- Swagger Configuration
- MassTransit/RabbitMQ Integration
- Health Checks
- Resilient HTTP Client
- Pagination Helper
- Middleware Setup
Installation
- Add the shared infrastructure project to your solution
- Reference the project in your API application
- Register services in your application startup:
- Call
AddSharedInfrastructure()
on your service collection
- Call
- Configure the middleware pipeline:
- Use
UseSharedInfrastructure()
for standard components - Add
UseSharedHealthChecks()
for health endpoints
- Use
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
- Register health checks with
AddSharedHealthChecks()
- Enable health endpoint with
UseSharedHealthChecks()
- 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:
- TimeZoneMiddleware
- Authentication
- Authorization
- Swagger documentation
- Health checks
- 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 | Versions 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. |
-
net9.0
- AspNetCore.HealthChecks.Npgsql (>= 9.0.0)
- AspNetCore.HealthChecks.Rabbitmq (>= 9.0.0)
- AspNetCore.HealthChecks.UI.Client (>= 9.0.0)
- AutoMapper (>= 14.0.0)
- MassTransit (>= 8.4.1)
- MassTransit.RabbitMQ (>= 8.4.1)
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 9.0.6)
- Microsoft.EntityFrameworkCore (>= 9.0.6)
- Microsoft.Extensions.Diagnostics.HealthChecks (>= 9.0.6)
- Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions (>= 9.0.6)
- Microsoft.Extensions.Http (>= 9.0.6)
- Microsoft.Extensions.Logging.Abstractions (>= 9.0.6)
- Npgsql.EntityFrameworkCore.PostgreSQL (>= 9.0.4)
- OpenTelemetry (>= 1.12.0)
- OpenTelemetry.Exporter.OpenTelemetryProtocol (>= 1.12.0)
- OpenTelemetry.Extensions.Hosting (>= 1.12.0)
- OpenTelemetry.Instrumentation.AspNetCore (>= 1.12.0)
- OpenTelemetry.Instrumentation.Http (>= 1.12.0)
- RabbitMQ.Client (>= 7.1.2)
- Refit (>= 8.0.0)
- Serilog.AspNetCore (>= 9.0.0)
- Serilog.Enrichers.Environment (>= 3.0.1)
- Serilog.Enrichers.Process (>= 3.0.0)
- Serilog.Enrichers.Thread (>= 4.0.0)
- Serilog.Sinks.Console (>= 6.0.0)
- Serilog.Sinks.File (>= 7.0.0)
- Serilog.Sinks.Grafana.Loki (>= 8.3.1)
- Serilog.Sinks.OpenTelemetry (>= 4.2.0)
- Swashbuckle.AspNetCore (>= 9.0.1)
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 |