Files
MegghysAPI/Program.cs
Megghy 7abe753401 1
2025-09-26 01:58:55 +08:00

85 lines
2.2 KiB
C#

using System.Diagnostics;
using System.Reflection;
using MegghysAPI.Attributes;
using MegghysAPI.Components;
using AntDesign;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
builder.Services.AddAntDesign();
builder.Services.AddControllers();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAntiforgery();
app.MapStaticAssets();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
app.UseRouting();
app.UseAntiforgery();
app.MapControllers();
// 加载所有有 AutoInitAttribute 的类
// 获取当前Assembly
var inits = new List<MethodInfo>();
foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
{
foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)
.Where(m => m.GetCustomAttribute<AutoInitAttribute>() is not null))
{
inits.Add(method);
}
}
DB.InitDB();
inits = inits
.OrderBy(m => m.GetCustomAttribute<AutoInitAttribute>()?.Order ?? 0)
.ToList();
foreach (var method in inits)
{
var sw = Stopwatch.StartNew();
var attr = method.GetCustomAttribute<AutoInitAttribute>();
if (attr?.LogMessage is { } message)
{
Logs.Info(message);
}
if (attr?.Async is true)
{
_ = Task.Run(() =>
{
method.Invoke(null, null);
attr.PostInit?.Invoke();
Logs.Info($"[{sw.ElapsedMilliseconds} ms] Async <{method.DeclaringType?.Name}.{method.Name}> => Inited.");
});
}
else
{
method.Invoke(null, null);
attr?.PostInit?.Invoke();
Logs.Info($"[{sw.ElapsedMilliseconds} ms] <{method.DeclaringType?.Name}.{method.Name}> => Inited.");
}
}
app.Run($"http://{Config.Instance.ListenHost}:{Config.Instance.ListenPort}");