Fortify.Extensions.DependencyInjection 1.0.3

dotnet add package Fortify.Extensions.DependencyInjection --version 1.0.3
                    
NuGet\Install-Package Fortify.Extensions.DependencyInjection -Version 1.0.3
                    
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="Fortify.Extensions.DependencyInjection" Version="1.0.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Fortify.Extensions.DependencyInjection" Version="1.0.3" />
                    
Directory.Packages.props
<PackageReference Include="Fortify.Extensions.DependencyInjection" />
                    
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 Fortify.Extensions.DependencyInjection --version 1.0.3
                    
#r "nuget: Fortify.Extensions.DependencyInjection, 1.0.3"
                    
#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 Fortify.Extensions.DependencyInjection@1.0.3
                    
#: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=Fortify.Extensions.DependencyInjection&version=1.0.3
                    
Install as a Cake Addin
#tool nuget:?package=Fortify.Extensions.DependencyInjection&version=1.0.3
                    
Install as a Cake Tool

🛡️ Fortify - 企业级 .NET 弹性策略库

.NET 8.0+ License: MIT PRs Welcome

Fortify 是一个功能强大、高度可扩展的 .NET 弹性和容错策略库,专为企业级应用设计。它提供了比 Polly 更丰富的功能集、更灵活的配置选项和更完善的监控能力。

✨ 核心特性

🔄 7种核心策略

  • Retry(重试) - 多种退避算法

    • 固定延迟、线性退避、指数退避(带抖动)
    • 自适应退避、自定义延迟数组
    • 条件重试、异常类型过滤
  • Circuit Breaker(断路器) - 防止级联故障

    • 传统断路器 + 滑动窗口断路器
    • 自动状态转换(Closed → Open → HalfOpen)
    • 慢调用检测、失败率计算
    • 手动控制(Reset、Isolate、Trip)
  • Timeout(超时) - 操作时间限制

    • 悲观超时 vs 乐观超时
    • 场景预设(FastApi、DatabaseQuery、FileUpload等)
    • 动态超时调整
  • Rate Limiting(限流) - 流量控制

    • 令牌桶、滑动窗口、固定窗口算法
    • 每秒/每分钟/每小时限流
    • 分布式限流支持(可扩展)
  • Fallback(降级) - 服务降级

    • 固定值降级、函数降级、链式降级
    • 异常类型过滤
    • 场景预设(网络错误、数据库错误)
  • Bulkhead(舱壁隔离) - 资源隔离

    • 信号量隔离、线程池隔离
    • 排队机制
    • 场景预设(高并发、IO密集、CPU密集)
  • Batch Executor(批量执行器) - 批处理

    • 并行执行、进度跟踪
    • 部分失败处理、失败重试
    • 批量超时控制

🚀 企业级增强功能

  • 🏗️ Builder 模式 - 流畅的 API 设计

    • 统一的 PolicyBuilder<T> API
    • 各策略专用 Builder(RetryPolicyBuilder、CircuitBreakerPolicyBuilder 等)
    • 25+ 场景预设(WebApi、Microservice、Database、FileUpload 等)
  • 📊 监控与指标 - 内置可观测性

    • 自动指标收集(成功率、延迟、吞吐量)
    • P50/P95/P99 延迟统计
    • 实时策略监控
    • 与 OpenTelemetry 兼容
  • 📝 结构化日志 - 完整的日志系统

    • 多种日志记录器(Console、File、Composite)
    • JSON 格式日志
    • 分布式追踪支持
    • 可扩展的日志接口
  • 🔍 执行上下文 - 丰富的元数据

    • CorrelationId、TraceId、SpanId
    • 多租户支持(UserId、TenantId)
    • 自定义数据字典
    • 上下文克隆与传递
  • 🏥 健康检查 - 服务健康监控

    • HTTP 健康检查、委托健康检查
    • 组合健康检查(All、Any、Majority 策略)
    • 健康状态缓存
    • 与策略集成
  • 🔐 幂等性支持 - 防止重复执行

    • 内存存储 + 可扩展存储接口
    • 并发请求处理
    • 失败结果缓存
    • 场景预设(支付、API请求、数据导入)
  • 🌐 ASP.NET Core 集成 - 开箱即用

    • 依赖注入支持
    • 配置文件加载(appsettings.json)
    • IPolicyRegistry 策略注册表
    • PolicyFactory 工厂模式

📦 安装

NuGet 包

# 核心库
dotnet add package Fortify.Core

# ASP.NET Core 集成(可选)
dotnet add package Fortify.Extensions.DependencyInjection

要求

  • .NET 8.0 或更高版本
  • C# 12.0 或更高版本

🚀 快速开始

1. 重试策略 - 自动重试失败的操作

using Fortify.Core.Retry;

// 创建重试策略
var retryPolicy = new RetryPolicyBuilder()
    .WithMaxRetryCount(3)
    .WithExponentialBackoff(TimeSpan.FromMilliseconds(100))
    .OnRetry((ex, attempt, delay) =>
        Console.WriteLine($"Retry {attempt} after {delay.TotalMilliseconds}ms due to {ex.Message}"))
    .Build();

// 执行操作
var result = retryPolicy.Execute(() =>
{
    // 你的业务逻辑
    return CallExternalService();
});

// 异步执行
var asyncResult = await retryPolicy.ExecuteAsync(async () =>
{
    return await CallExternalServiceAsync();
});

2. 断路器 - 防止级联故障

using Fortify.Core.CircuitBreaker;

// 传统断路器
var circuitBreaker = new CircuitBreakerPolicyBuilder()
    .WithFailureThreshold(5)  // 5次失败后打开
    .WithOpenDurationSeconds(30)  // 打开30秒
    .WithSuccessThreshold(2)  // 半开状态下2次成功后关闭
    .OnStateChange((oldState, newState) =>
        Console.WriteLine($"断路器状态: {oldState} → {newState}"))
    .Build();

// 滑动窗口断路器(更先进)
var slidingBreaker = new SlidingWindowCircuitBreakerBuilder()
    .UseCountBasedWindow(20)  // 最近20次调用
    .WithFailureRateThreshold(0.5)  // 50%失败率触发
    .WithSlowCallThreshold(TimeSpan.FromSeconds(2), 0.5)  // 慢调用检测
    .Build();

// 执行操作
try
{
    var result = circuitBreaker.Execute(() => CallUnstableService());
}
catch (CircuitBreakerOpenException ex)
{
    Console.WriteLine($"断路器打开,{ex.RetryAfter.TotalSeconds}秒后重试");
}

3. 限流 - 控制请求速率

using Fortify.Core.RateLimiting;

// 简化的限流策略
var rateLimitPolicy = new RateLimitPolicyBuilder()
    .WithRequestsPerSecond(10)  // 每秒10个请求
    .ThrowOnRejection(false)  // 超限时返回null而不抛异常
    .OnRejected(() => Console.WriteLine("⚠️ 请求被限流"))
    .Build();

// 高级限流配置
var advancedRateLimit = new RateLimitPolicyBuilder()
    .WithTokenBucket(
        capacity: 100,  // 桶容量
        tokensPerInterval: 50,  // 每次补充50个令牌
        refillInterval: TimeSpan.FromSeconds(1))
    .Build();

// 滑动窗口限流(精确控制)
var slidingWindowPolicy = new RateLimitPolicyBuilder()
    .WithSlidingWindow(100, TimeSpan.FromMinutes(1))  // 1分钟内最多100个请求
    .Build();

// 执行操作
var result = await rateLimitPolicy.ExecuteAsync(async () =>
{
    return await CallRateLimitedApi();
});

if (result == null)
{
    Console.WriteLine("请求被限流,请稍后重试");
}

4. 统一的 PolicyBuilder - 一站式策略组合

using Fortify.Core;

// 使用统一的 PolicyBuilder 构建完整的策略链
var policy = new PolicyBuilder<string>()
    .WithRateLimit(100, TimeSpan.FromSeconds(1))  // 限流:每秒100次
    .WithBulkhead(50, 100)  // 舱壁:50并发,100排队
    .WithCircuitBreaker(5, TimeSpan.FromSeconds(30))  // 断路器:5次失败
    .WithRetry(3, TimeSpan.FromMilliseconds(100))  // 重试:3次,100ms延迟
    .WithTimeoutSeconds(10)  // 超时:10秒
    .WithFallback("降级响应")  // 降级:返回默认值
    .Build();

// 执行操作
var result = await policy.ExecuteAsync(async () =>
{
    return await CallExternalService();
});

// 或使用传统的策略组合
var policyWrap = new PolicyWrap(rateLimit, circuitBreaker, retry);

// 捕获详细的执行结果
var executionResult = await policy.ExecuteAndCaptureAsync(async () =>
{
    return await CallExternalService();
});

if (executionResult.IsSuccess)
{
    Console.WriteLine($"✅ 成功!结果: {executionResult.Value}");
    Console.WriteLine($"   尝试次数: {executionResult.TotalAttempts}");
    Console.WriteLine($"   总耗时: {executionResult.TotalDuration.TotalMilliseconds}ms");
}
else
{
    Console.WriteLine($"❌ 失败,共尝试 {executionResult.TotalAttempts} 次");
    Console.WriteLine($"   异常: {executionResult.Exception?.Message}");
}

5. 使用预设策略 - 开箱即用

using Fortify.Core.Presets;

// Web API 调用策略(超时10秒 + 重试5次 + 断路器)
var webApiPolicy = CommonPolicies.WebApiPolicy();

// 微服务调用策略(限流 + 舱壁 + 断路器 + 重试 + 超时)
var microservicePolicy = CommonPolicies.MicroservicePolicy();

// 数据库操作策略(超时30秒 + 重试4次)
var databasePolicy = CommonPolicies.DatabasePolicy();

// 文件上传策略(舱壁5并发 + 超时5分钟 + 快速重试)
var fileUploadPolicy = CommonPolicies.FileUploadPolicy();

// 第三方API策略(限流60次/分钟 + 长超时 + 容错断路器)
var thirdPartyApiPolicy = CommonPolicies.ThirdPartyApiPolicy();

// 使用预设策略
var result = await webApiPolicy.ExecuteAsync(async () =>
{
    return await CallWebApi();
});

6. ASP.NET Core 集成

// Program.cs
using Fortify.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

// 方式1: 基础注册
builder.Services.AddFortify();

// 方式2: 从配置文件加载
builder.Services.AddFortify(builder.Configuration.GetSection("Fortify"));

// 方式3: 添加预设策略
builder.Services.AddWebApiPolicy("MyApiPolicy");
builder.Services.AddDatabasePolicy("MyDbPolicy");

var app = builder.Build();
// Controller.cs
public class WeatherController : ControllerBase
{
    private readonly IPolicyRegistry _policyRegistry;
    
    public WeatherController(IPolicyRegistry policyRegistry)
    {
        _policyRegistry = policyRegistry;
    }
    
    [HttpGet]
    public async Task<IActionResult> Get()
    {
        var policy = _policyRegistry.Get<string>("MyApiPolicy");
        
        var result = await policy.ExecuteAsync(async () =>
        {
            return await _weatherService.GetWeatherAsync();
        });
        
        return Ok(result);
    }
}
// appsettings.json
{
  "Fortify": {
    "Retry": {
      "MaxRetryCount": 3,
      "BaseDelay": "00:00:00.100",
      "BackoffType": "Exponential"
    },
    "CircuitBreaker": {
      "FailureThreshold": 5,
      "OpenDuration": "00:00:30",
      "SuccessThreshold": 2
    },
    "Timeout": {
      "DefaultTimeout": "00:00:10"
    }
  }
}

🎯 高级功能

1. 执行上下文 - 分布式追踪与多租户

using Fortify.Core;
using ExecutionContext = Fortify.Core.ExecutionContext;

// 创建带追踪信息的上下文
var context = new ExecutionContext()
    .WithTracing("trace-12345", "span-67890")  // 分布式追踪
    .WithUser("user-001", "tenant-A")  // 多租户
    .WithTag("production")
    .WithData("orderId", "ORD-12345")
    .WithData("priority", "high");

// 在策略中使用上下文
var result = await policy.ExecuteAsync(async () =>
{
    return await ProcessOrder();
}, context);

// 上下文会自动传递到日志和监控系统
Console.WriteLine($"TraceId: {context.TraceId}");
Console.WriteLine($"User: {context.UserId}@{context.TenantId}");

2. 监控与指标 - 实时可观测性

using Fortify.Core.Monitoring;

// 创建带监控的策略
var policy = Policy.Retry(3)
    .WithMetrics("MyRetryPolicy");  // 启用指标收集

// 执行操作
await policy.ExecuteAsync(async () => await CallService());

// 查看实时指标
var metrics = PolicyMonitor.Instance.GetMetrics("MyRetryPolicy");
var snapshot = metrics.GetSnapshot();

Console.WriteLine($"总执行次数: {snapshot.TotalExecutions}");
Console.WriteLine($"成功率: {snapshot.SuccessRate:P2}");
Console.WriteLine($"平均延迟: {snapshot.AverageExecutionTimeMs:F2}ms");
Console.WriteLine($"P95延迟: {snapshot.P95LatencyMs:F2}ms");
Console.WriteLine($"P99延迟: {snapshot.P99LatencyMs:F2}ms");

// 获取全局报告
var report = PolicyMonitor.Instance.GetSummaryReport();
Console.WriteLine(report);

// 找出性能最慢的策略
var slowest = PolicyMonitor.Instance.GetSlowestPolicies(5);
foreach (var policy in slowest)
{
    Console.WriteLine($"{policy.PolicyName}: P95={policy.P95LatencyMs:F2}ms");
}

3. 结构化日志 - 完整的日志记录

using Fortify.Core.Logging;

// 创建带日志的策略
var policy = new RetryPolicyBuilder()
    .WithMaxRetryCount(3)
    .Build()
    .WithLogging(new ConsolePolicyLogger(prettyPrint: true));

// 或使用自定义日志记录器
var fileLogger = new CustomFileLogger("policy-logs.txt");
var consoleLogger = new ConsolePolicyLogger();
var compositeLogger = new CompositePolicyLogger(fileLogger, consoleLogger);

var policyWithLogging = retry.WithLogging(compositeLogger);

// 执行操作,日志会自动记录
await policyWithLogging.ExecuteAsync(async () =>
{
    return await CallService();
}, context);

4. 健康检查 - 服务健康监控

using Fortify.Core.HealthCheck;

// HTTP 健康检查
var apiCheck = new HttpHealthCheck(
    name: "UserService",
    url: "https://api.example.com/health",
    timeout: TimeSpan.FromSeconds(5)
);

// 委托健康检查
var databaseCheck = new DelegateHealthCheck(
    name: "Database",
    check: () => CheckDatabaseConnection(),
    description: "PostgreSQL 数据库连接"
);

// 组合健康检查(所有服务都必须健康)
var allServicesCheck = new CompositeHealthCheck("AllServices", CompositeHealthCheckStrategy.All)
    .AddCheck(apiCheck)
    .AddCheck(databaseCheck);

// 检查健康状态
var result = await allServicesCheck.CheckHealthAsync();
Console.WriteLine($"状态: {result.Status}");  // Healthy, Degraded, Unhealthy

// 与策略集成
var healthCheckPolicy = new HealthCheckPolicy(
    allServicesCheck,
    new HealthCheckOptions
    {
        AllowDegraded = true,
        CacheDuration = TimeSpan.FromSeconds(30)
    }
);

var combinedPolicy = new PolicyWrap(healthCheckPolicy, retryPolicy);

5. 幂等性支持 - 防止重复执行

using Fortify.Core.Idempotency;

// 创建幂等性策略
var idempotencyPolicy = new IdempotencyPolicyBuilder<PaymentResult>()
    .UseInMemoryStore()  // 或使用 Redis/数据库存储
    .WithKeyGenerator(ctx => $"payment:{ctx.UserId}:{ctx.GetData<string>("orderId")}")
    .ForPayment()  // 24小时过期,缓存失败结果
    .OnCacheHit((key, result) => Console.WriteLine($"💰 检测到重复支付请求"))
    .OnCacheMiss((key, result) => Console.WriteLine($"💳 首次支付请求"))
    .Build();

// 执行支付(多次点击只会执行一次)
var context = new ExecutionContext()
    .WithUser("user-001")
    .WithData("orderId", "ORD-12345");

for (int i = 0; i < 3; i++)
{
    var result = await idempotencyPolicy.ExecuteAsync(async () =>
    {
        Console.WriteLine("执行扣款操作");
        return await ProcessPayment(orderId, amount);
    }, context);
    
    Console.WriteLine($"第{i + 1}次请求: {result.TransactionId}");
}
// 输出:只有第一次会执行扣款,后续返回缓存结果

6. 批量执行器 - 高效批处理

using Fortify.Core.Batch;

// 创建批量执行器
var executor = new BatchExecutor();

// 批量处理数据
var items = Enumerable.Range(1, 100).ToList();

var options = new BatchExecutionOptions
{
    MaxDegreeOfParallelism = 10,  // 10个并发
    ContinueOnError = true,  // 遇到错误继续
    TrackProgress = true  // 跟踪进度
};

var result = await executor.ExecuteAsync(
    items,
    async item =>
    {
        await Task.Delay(100);
        return item * 2;
    },
    options,
    progress: p => Console.WriteLine($"进度: {p.Percentage:F1}%")
);

Console.WriteLine($"成功: {result.SuccessCount}");
Console.WriteLine($"失败: {result.FailureCount}");
Console.WriteLine($"成功率: {result.SuccessRate:P2}");

// 处理失败项
if (result.HasFailures)
{
    var failedItems = result.Failures
        .Select(f => items[f.Index])
        .ToList();
    
    // 重试失败项
    var retryResult = await executor.ExecuteAsync(failedItems, processFunc, options);
}

7. 自定义延迟数组 - 精确控制重试间隔

// 针对不同场景的自定义重试策略
var customRetry = new RetryPolicyBuilder()
    .WithMaxRetryCount(6)
    .WithCustomDelays(
        TimeSpan.FromMilliseconds(100),   // 1st: 网络抖动
        TimeSpan.FromMilliseconds(200),   // 2nd: 网络抖动
        TimeSpan.FromMilliseconds(500),   // 3rd: 短暂故障
        TimeSpan.FromSeconds(1),          // 4th: 服务问题
        TimeSpan.FromSeconds(3),          // 5th: 服务恢复
        TimeSpan.FromSeconds(10))         // 6th+: 长时间等待
    .Build();

8. 多种退避策略

// 线性退避
var linearRetry = new RetryPolicyBuilder()
    .WithLinearBackoff(TimeSpan.FromSeconds(1), useJitter: true)
    .Build();

// 自适应退避(根据异常类型动态调整)
var adaptiveRetry = new RetryPolicyBuilder()
    .WithAdaptiveBackoff(
        baseDelay: TimeSpan.FromMilliseconds(100),
        maxDelay: TimeSpan.FromSeconds(10),
        historySize: 20)
    .Build();

// 自定义退避函数
var customBackoff = new RetryPolicyBuilder()
    .WithCustomBackoff((attempt, lastException) =>
    {
        // 根据异常类型返回不同的延迟
        if (lastException is TimeoutException)
            return TimeSpan.FromSeconds(5);
        if (lastException is HttpRequestException)
            return TimeSpan.FromSeconds(2);
        return TimeSpan.FromSeconds(1);
    })
    .Build();

📁 项目结构

Fortify/
├── src/
│   ├── Fortify.Core/                                # 核心库
│   │   ├── Policy.cs                                # 策略入口
│   │   ├── PolicyBuilder.cs                         # 统一的策略构建器
│   │   ├── ExecutionContext.cs                      # 执行上下文
│   │   ├── ExecutionResult.cs                       # 执行结果
│   │   ├── PolicyWrap.cs                            # 策略组合器
│   │   ├── Retry/                                   # 重试策略
│   │   │   ├── RetryPolicy.cs
│   │   │   ├── RetryPolicyBuilder.cs
│   │   │   └── BackoffStrategies/                   # 退避策略
│   │   ├── CircuitBreaker/                          # 断路器
│   │   │   ├── CircuitBreakerPolicy.cs
│   │   │   ├── SlidingWindowCircuitBreaker.cs       # 滑动窗口断路器
│   │   │   └── CircuitBreakerPolicyBuilder.cs
│   │   ├── Timeout/                                 # 超时策略
│   │   │   ├── TimeoutPolicy.cs
│   │   │   └── TimeoutPolicyBuilder.cs
│   │   ├── RateLimiting/                            # 限流策略
│   │   │   ├── RateLimitPolicy.cs
│   │   │   ├── TokenBucketRateLimiter.cs
│   │   │   ├── SlidingWindowRateLimiter.cs
│   │   │   └── RateLimitPolicyBuilder.cs
│   │   ├── Fallback/                                # 降级策略
│   │   │   ├── FallbackPolicy.cs
│   │   │   ├── FallbackChain.cs
│   │   │   └── FallbackPolicyBuilder.cs
│   │   ├── Bulkhead/                                # 舱壁隔离
│   │   │   ├── BulkheadPolicy.cs
│   │   │   └── BulkheadPolicyBuilder.cs
│   │   ├── Batch/                                   # 批量执行器
│   │   │   ├── BatchExecutor.cs
│   │   │   ├── BatchResult.cs
│   │   │   └── BatchExecutionOptions.cs
│   │   ├── Monitoring/                              # 监控与指标
│   │   │   ├── PolicyMonitor.cs
│   │   │   ├── PolicyMetrics.cs
│   │   │   └── MetricsExtensions.cs
│   │   ├── Logging/                                 # 日志系统
│   │   │   ├── IPolicyLogger.cs
│   │   │   ├── ConsolePolicyLogger.cs
│   │   │   └── CompositePolicyLogger.cs
│   │   ├── HealthCheck/                             # 健康检查
│   │   │   ├── IHealthCheck.cs
│   │   │   ├── HttpHealthCheck.cs
│   │   │   ├── CompositeHealthCheck.cs
│   │   │   └── HealthCheckPolicy.cs
│   │   ├── Idempotency/                             # 幂等性支持
│   │   │   ├── IdempotencyPolicy.cs
│   │   │   ├── IdempotencyPolicyBuilder.cs
│   │   │   └── IIdempotencyStore.cs
│   │   ├── Presets/                                 # 预设策略
│   │   │   └── CommonPolicies.cs                    # 25+场景预设
│   │   └── Extensions/                              # 扩展方法
│   │       └── PolicyExtensions.cs
│   │
│   └── Fortify.Extensions.DependencyInjection/      # ASP.NET Core 集成
│       ├── FortifyServiceCollectionExtensions.cs    # 服务注册
│       ├── IPolicyRegistry.cs                       # 策略注册表
│       ├── PolicyFactory.cs                         # 策略工厂
│       └── FortifyOptions.cs                        # 配置选项
│
├── examples/
│   └── Fortify.Examples/                            # 示例代码
│       ├── Program.cs                               # 示例入口
│       ├── BasicFeaturesExample.cs                  # 基础功能
│       ├── AdvancedFeaturesExample.cs               # 高级功能
│       ├── ExecutionContextExample.cs               # 执行上下文
│       ├── StructuredLoggingExample.cs              # 结构化日志
│       ├── HealthCheckExample.cs                    # 健康检查
│       ├── IdempotencyExample.cs                    # 幂等性
│       └── ...                                      # 更多示例
│
├── tests/
│   └── Fortify.Tests/                               # 单元测试
│       ├── RetryPolicyTests.cs
│       ├── CircuitBreakerPolicyTests.cs
│       └── ...
│
└── docs/                                            # 文档
    ├── Architecture-Design.md                       # 架构设计
    ├── Feature-Comparison.md                        # 功能对比
    └── Implementation-Progress.md                   # 实现进度

📊 与 Polly 的功能对比

功能特性 Fortify Polly
核心策略
重试 (Retry) ✅ 5种退避算法 ✅ 3种
断路器 (Circuit Breaker) ✅ 传统+滑动窗口 ✅ 传统
超时 (Timeout) ✅ 悲观+乐观+预设 ✅ 基础
限流 (Rate Limiting) ✅ 3种算法+预设 ✅ 基础
降级 (Fallback) ✅ 链式+预设 ✅ 单一
舱壁 (Bulkhead) ✅ 信号量+线程池 ✅ 信号量
批量执行器 (Batch) ✅ 完整支持
增强功能
统一 Builder API ✅ PolicyBuilder<T>
预设策略(25+) ✅ 场景化预设
执行上下文 ✅ 分布式追踪+多租户 ⚠️ 基础
监控指标 ✅ 实时+P95/P99 ⚠️ 需扩展
结构化日志 ✅ 多种日志器 ⚠️ 需扩展
健康检查 ✅ 完整系统
幂等性支持 ✅ 内置支持
ASP.NET Core 集成 ✅ 开箱即用 ⚠️ 需配置
配置文件支持 ✅ appsettings.json ⚠️ 需扩展
性能与可扩展性
异步性能 ✅ 优化
内存占用 ✅ 低
线程安全 ✅ 完全
可扩展性 ✅ 接口驱动

💡 为什么选择 Fortify?

  1. 更丰富的功能集 - 7种核心策略 + 8大增强功能,开箱即用
  2. 统一的 API 设计 - PolicyBuilder<T> 提供一致的开发体验
  3. 25+ 场景预设 - 针对 Web API、微服务、数据库等常见场景
  4. 内置可观测性 - 监控、日志、追踪一应俱全
  5. ASP.NET Core 优先 - 完美集成依赖注入和配置系统
  6. 企业级特性 - 幂等性、健康检查、批量处理等高级功能

🎨 示例代码

完整的示例代码请查看 examples/Fortify.Examples/ 目录,包含:

  • ✅ 18个完整的示例程序
  • ✅ 涵盖所有核心功能
  • ✅ 真实场景演示
  • ✅ 最佳实践展示

运行示例:

cd examples/Fortify.Examples
dotnet run

🧪 运行测试

# 运行所有测试
dotnet test

# 运行特定测试
dotnet test --filter "FullyQualifiedName~RetryPolicyTests"

# 生成代码覆盖率报告
dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=opencover

📖 文档

🤝 贡献指南

我们欢迎各种形式的贡献!

如何贡献

  1. Fork 本仓库
  2. 创建您的特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交您的更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 开启一个 Pull Request

贡献内容

  • 🐛 报告 Bug
  • 💡 提出新功能建议
  • 📝 改进文档
  • ✨ 提交代码
  • 🧪 编写测试

📝 更新日志

查看 CHANGELOG.md 了解每个版本的更新内容。

📄 许可证

本项目基于 MIT License 开源。

💬 联系我们

🌟 致谢

感谢所有贡献者和使用 Fortify 的开发者们!


Made with ❤️ by the Fortify Team

回到顶部 ↑

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  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.0.3 277 11/10/2025
1.0.2 216 11/9/2025
1.0.1 214 11/9/2025
1.0.0 214 11/9/2025

v1.0.3: Documentation improvements - Fixed README HTML tags rendering on NuGet.org by converting to pure Markdown syntax. Updated to use Fortify.Core 1.0.2