第一步:定义注入类型
public class CurdAfterLog : IDisposable
{
public static AsyncLocal<CurdAfterLog> Current = new AsyncLocal<CurdAfterLog>();
public StringBuilder Sb { get; } = new StringBuilder();
public CurdAfterLog()
{
Current.Value = this;
}
public void Dispose()
{
Sb.Clear();
Current.Value = null;
}
}
第二步:注入 CurdAfterLog
services.AddSingleton<IFreeSql>(fsql);
services.AddScoped<CurdAfterLog>();
第三步:添加 CurdAfter 事件
fsql.Aop.CurdAfter += (s, e) =>
{
CurdAfterLog.Current.Value?.Sb.AppendLine($"{Thread.CurrentThread.ManagedThreadId}: {e.EntityType.FullName} {e.ElapsedMilliseconds}ms, {e.Sql}");
};
便于管理 fsql.Aop.CurdAfter 应该和 new FreeSqlBuilder()..Build() 代码放在一起,并且该事件只绑定一次
第四步:在 Controller 中测试
public class ValuesController : ControllerBase
{
IFreeSql _fsql;
CurdAfterLog _curdLog;
public ValuesController(IFreeSql fsql, CurdAfterLog curdLog)
{
_fsql = fsql;
_curdLog = curdLog;
}
public ActionResult<string> Get(int id)
{
var item1 = _orm.Select<Song>().Where(a => a.Id == id).First();
var item2 = _orm.Select<Song>().Where(a => a.Id == id).First();
return _curdLog.Sb.ToString();
}
}