using Hangfire; using Hangfire.SqlServer; using Microsoft.AspNetCore.Builder; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Identity.Client; using System; using System.Reflection; using System.Text.Json; using System.Text.Json.Serialization; using TaskManager.EntityFramework; var builder = WebApplication.CreateBuilder(args); // 从配置中获取连接字符串 var defaultConnection = builder.Configuration.GetConnectionString("Default"); builder.Services.AddHttpClient(); //builder.Services.AddScoped(); //builder.Services.AddScoped(); //builder.Services.AddScoped(); //builder.Services.AddControllers() // .AddJsonOptions(options => // { // options.JsonSerializerOptions.Converters.Add(new CustomDateTimeConverter("yyyy-MM-dd HH:mm:ss")); // options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); // }); // 添加服务到容器 builder.Services.AddControllers(); // 配置 JSON 序列化选项(从配置中读取策略) var jsonNamingPolicy = builder.Configuration.GetValue("JsonOptions:PropertyNamingPolicy"); if (jsonNamingPolicy == "CamelCase") { builder.Services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; }); } // 可选:支持其他命名策略(如 PascalCase) else if (jsonNamingPolicy == "PascalCase") { // ... } //builder.Services.AddTransient(); // 配置 DbContext 使用 SQL Server 连接字符串 builder.Services.AddDbContext(options => options.UseSqlServer(defaultConnection)); // 配置 Hangfire 使用 SQL Server 存储 builder.Services.AddHangfire( configuration => configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) // 建议显式设置兼容性版本 .UseSimpleAssemblyNameTypeSerializer() // 简化类型序列化(可选) .UseRecommendedSerializerSettings() // 使用推荐的序列化设置(可选) .UseSqlServerStorage(defaultConnection, new SqlServerStorageOptions { // 可从配置中读取 Hangfire 存储选项(如队列、重试策略等) CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), QueuePollInterval = TimeSpan.Zero, UseRecommendedIsolationLevel = true, DisableGlobalLocks = true }) //.UseFilter(builder.Services.BuildServiceProvider().GetRequiredService>()) ); // 添加日志过滤器(可选) // 配置 Hangfire 服务器(可从配置中读取工作线程数等) var workerCount = builder.Configuration.GetValue("Hangfire:ServerOptions:WorkerCount", 10); // 默认值 10 builder.Services.AddHangfireServer(options => { options.WorkerCount = workerCount; // 可选:配置队列优先级 options.Queues = builder.Configuration.GetSection("Hangfire:ServerOptions:Queues").Get() ?? new[] { "default" }; }); // 添加 Swagger 等其他服务... builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); app.UseHangfireDashboard(); // 配置中间件... if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseAuthorization(); app.MapControllers(); app.Run(); // 示例泛型方法