LFlow/LFlow.Base/Program.cs

167 lines
5.8 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 System.Reflection;
using LFlow.Base.Interfaces;
using LFlow.Base.Utils;
using Serilog;
using Serilog.Events;
using SqlSugar;
namespace LFlow.Base;
public static class Program
{
public static void Main(string[] args)
{
// 先用Serilog的BootstrapLogger
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateBootstrapLogger();
var builder = WebApplication.CreateBuilder(args);
// 添加到Service中
builder.Services.AddSerilog((services, lc) => lc
.ReadFrom.Configuration(builder.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext()
// .WriteTo.Console()
);
Log.Logger.Information("LoadSubService");
builder.Services.LoadSubService();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddHttpContextAccessor();
Log.Logger.Information("ConfigureSqlSugar");
builder.Services.ConfigureSqlSugar();
builder.Services.AddControllers();
builder.Services.AddSwaggerGen(u =>
{
u.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
{
Version = "Ver.1",
Title = "LFlow",
Description = "LFlow api test and document",
Contact = new Microsoft.OpenApi.Models.OpenApiContact
{
Name = "ling",
Email = "noemail@ling.chat"
}
});
});
// 使用Serilog此处为了修复 `The logger is already frozen` 的问题重新配置Serilog
builder.Host.UseSerilog((context, services, config) =>
{
config.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext();
// .WriteTo.Console();
}, true);
// init App.service
App.services = builder.Services;
var app = builder.Build();
app.UseSerilogRequestLogging(options =>
{
// 配置日志级别
options.GetLevel = (httpContext, elapsed, ex) => LogEventLevel.Information;
});
app.MapControllers();
// app.MapGet("/", () => "Hello World!");
// if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(u =>
{
u.DocumentTitle = "LFlow";
});
}
// 在启动后调用Sqlsugar进行CodeFirst
// 挂载启动后事件
app.Services.GetRequiredService<IHostApplicationLifetime>().ApplicationStarted.Register(() =>
{
Log.Logger.Information("ApplicationStarted");
CodeFirst.InitTable();
});
app.Run();
}
public static void ConfigureSqlSugar(this IServiceCollection services)
{
services.AddSingleton<ISqlSugarClient>(s =>
{
SqlSugarScope sqlSugar = new(new ConnectionConfig()
{
DbType = SqlSugar.DbType.Sqlite,
ConnectionString = "DataSource=LFlow-dev.db",
IsAutoCloseConnection = true,
},
db =>
{
//单例参数配置,所有上下文生效
db.Aop.OnLogExecuting = (sql, pars) =>
{
//获取作IOC作用域对象
var appServive = s.GetService<IHttpContextAccessor>();
// var obj = appServive?.HttpContext?.RequestServices.GetService<Log>();
// Console.WriteLine("AOP" + obj.GetHashCode());
Console.WriteLine($"{appServive?.HttpContext?.Request.Path}:{sql}\r\n{pars}");
};
});
sqlSugar.DbMaintenance.CreateDatabase();
return sqlSugar;
});
}
/// <summary>
/// 从子文件夹中加载DLL
/// </summary>
public static void LoadSubService(this IServiceCollection services)
{
var path = Path.Combine(AppContext.BaseDirectory, "Services");
// Console.WriteLine(path);
var files = Directory.GetFiles(path, "*.dll");
try
{
foreach (var file in files)
{
Log.Logger.Information($"Load file -> {file}...");
var assembly = Assembly.LoadFile(file);
var types = assembly.GetTypes();
// bool isUseController = false;
foreach (var type in types)
{
// Console.WriteLine(type);
if (type.IsClass && !type.IsAbstract)
{
var interfaces = type.GetInterfaces();
if (interfaces.Contains(typeof(IModule)))
{
Log.Logger.Information($"\tFound IModule -> {type.FullName}");
var module = Activator.CreateInstance(type) as IModule;
module?.ConfigureModule(services);
}
}
}
// if (isUseController)
// {
// Log.Logger.Information($"\tAdd Controllers for {assembly.FullName}");
// // 添加Controller
// services.AddControllers().AddApplicationPart(assembly);
// }
Log.Logger.Information("done.\r\n");
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.ToString());
throw;
}
}
}