using Kurisu.AspNetCore.Startup; using Kurisu.Core.DataAccess.Entity; using Kurisu.SqlSugar.Extensions; using Kurisu.SqlSugar.Services; using Microsoft.AspNetCore.Mvc.Filters; using SqlSugar; namespace Dlhis.Sys; public class SqlSugarPack : BaseAppPack { public override bool IsBeforeUseRouting { get; } public override void ConfigureServices(IServiceCollection services) { services.AddSqlSugar(); } } /// /// 日志 /// [AttributeUsage(AttributeTargets.Method)] public class LogAttribute : Attribute, IAsyncActionFilter { public LogAttribute(string title) { Title = title; } /// /// /// public string Title { get; set; } /// /// 是否处理差异 /// public bool Diff { get; set; } public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { PreSetting(context.HttpContext); await next(); } private void PreSetting(HttpContext httpContext) { var options = httpContext.RequestServices.GetService(); options.Title = Title; options.Diff = Diff; options.BatchNo = Guid.NewGuid(); options.RoutePath = httpContext.Request.Path.Value; options.RaiseTime = DateTime.Now; } } /// /// 事务 /// [AttributeUsage(AttributeTargets.Method)] public class TransactionalAttribute : Attribute, IAsyncActionFilter { public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { var dbContext = context.HttpContext.RequestServices.GetRequiredService(); await dbContext.Ado.BeginTranAsync(); try { var result = await next(); if (result.Exception != null) { throw result.Exception; } else { await dbContext.Ado.CommitTranAsync(); } } catch (Exception) { await dbContext.Ado.RollbackTranAsync(); throw; } } } /// /// 忽略租户 /// [AttributeUsage(AttributeTargets.Method)] public class IgnoreTenantAttribute : Attribute, IAsyncActionFilter { public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { var dbContext = context.HttpContext.RequestServices.GetRequiredService(); var options = context.HttpContext!.RequestServices.GetService(); try { dbContext.QueryFilter.ClearAndBackup(); options.IgnoreTenant = true; await next(); } finally { options.IgnoreTenant = false; dbContext.QueryFilter.Restore(); } } }