Files
petwash/PetWash.Api/Program.cs
2026-03-03 16:49:57 +08:00

87 lines
2.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Microsoft.EntityFrameworkCore;
using PetWash.Api.Data;
using PetWash.Api.Services;
var builder = WebApplication.CreateBuilder(args);
// 配置数据库(支持 SQLite 和 MySQL
var dbProvider = builder.Configuration.GetValue<string>("DatabaseProvider") ?? "Sqlite";
var connectionString = dbProvider == "MySql"
? builder.Configuration.GetConnectionString("MySqlConnection")
: builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<PetWashDbContext>(options =>
{
if (dbProvider == "MySql")
{
var serverVersion = new MySqlServerVersion(new Version(8, 0, 21));
options.UseMySql(connectionString, serverVersion);
}
else
{
options.UseSqlite(connectionString ?? "Data Source=petwash.db");
}
});
// 添加服务
builder.Services.AddSingleton<MqttService>();
builder.Services.AddHostedService(provider => provider.GetRequiredService<MqttService>());
builder.Services.AddScoped<OrderService>();
// 添加CORS
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// 初始化数据库
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<PetWashDbContext>();
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
try
{
logger.LogInformation("开始初始化数据库...");
// 确保数据库已创建
var created = db.Database.EnsureCreated();
if (created)
{
logger.LogInformation("数据库创建成功,种子数据已插入");
}
else
{
logger.LogInformation("数据库已存在");
}
}
catch (Exception ex)
{
logger.LogError(ex, "数据库初始化失败");
throw;
}
}
// 启用 Swagger所有环境
app.UseSwagger();
app.UseSwaggerUI();
app.UseCors();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();