112 lines
3.0 KiB
C#
112 lines
3.0 KiB
C#
using Autofac;
|
||
using Autofac.Extensions.DependencyInjection;
|
||
using HoneyBox.Api.Filters;
|
||
using HoneyBox.Core.Mappings;
|
||
using HoneyBox.Infrastructure.Cache;
|
||
using HoneyBox.Infrastructure.Modules;
|
||
using HoneyBox.Model.Data;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using Scalar.AspNetCore;
|
||
using Serilog;
|
||
|
||
// 配置 Serilog
|
||
Log.Logger = new LoggerConfiguration()
|
||
.ReadFrom.Configuration(new ConfigurationBuilder()
|
||
.AddJsonFile("appsettings.json")
|
||
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
|
||
.Build())
|
||
.CreateLogger();
|
||
|
||
try
|
||
{
|
||
Log.Information("Starting HoneyBox API...");
|
||
|
||
var builder = WebApplication.CreateBuilder(args);
|
||
|
||
// 使用 Serilog
|
||
builder.Host.UseSerilog();
|
||
|
||
// 使用 Autofac 作为依赖注入容器
|
||
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
|
||
builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
|
||
{
|
||
// 注册基础设施模块
|
||
containerBuilder.RegisterModule<InfrastructureModule>();
|
||
// 注册服务模块
|
||
containerBuilder.RegisterModule<ServiceModule>();
|
||
});
|
||
|
||
// 配置 DbContext
|
||
builder.Services.AddDbContext<HoneyBoxDbContext>(options =>
|
||
{
|
||
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
|
||
});
|
||
|
||
// 配置 Mapster
|
||
builder.Services.AddMapsterConfiguration();
|
||
|
||
// 注册 Redis 缓存服务(通过 Autofac 模块注册,这里添加 IConfiguration)
|
||
builder.Services.AddSingleton<ICacheService>(sp =>
|
||
new RedisCacheService(builder.Configuration));
|
||
|
||
// 添加控制器
|
||
builder.Services.AddControllers(options =>
|
||
{
|
||
// 添加全局异常过滤器
|
||
options.Filters.Add<GlobalExceptionFilter>();
|
||
});
|
||
|
||
// 配置 OpenAPI(.NET 10 内置支持)
|
||
builder.Services.AddOpenApi();
|
||
|
||
|
||
// 配置 CORS(仅开发环境,生产环境由 Nginx 处理)
|
||
builder.Services.AddCors(options =>
|
||
{
|
||
options.AddPolicy("Development", policy =>
|
||
{
|
||
policy.AllowAnyOrigin()
|
||
.AllowAnyMethod()
|
||
.AllowAnyHeader();
|
||
});
|
||
});
|
||
|
||
var app = builder.Build();
|
||
|
||
// 配置 HTTP 请求管道
|
||
if (app.Environment.IsDevelopment())
|
||
{
|
||
// 使用 OpenAPI 和 Scalar UI
|
||
app.MapOpenApi();
|
||
app.MapScalarApiReference();
|
||
|
||
// 仅开发环境启用 CORS,生产环境由 Nginx 配置
|
||
app.UseCors("Development");
|
||
}
|
||
|
||
// 使用 Serilog 请求日志
|
||
app.UseSerilogRequestLogging();
|
||
|
||
// 使用路由
|
||
app.UseRouting();
|
||
|
||
// 使用授权(后续添加 JWT 认证时启用)
|
||
// app.UseAuthentication();
|
||
// app.UseAuthorization();
|
||
|
||
// 映射控制器
|
||
app.MapControllers();
|
||
|
||
Log.Information("HoneyBox API started successfully");
|
||
|
||
app.Run();
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Log.Fatal(ex, "Application terminated unexpectedly");
|
||
}
|
||
finally
|
||
{
|
||
Log.CloseAndFlush();
|
||
}
|