.NET 8.0中使用MiniProfiler监控数据库查询
StackExchange.Profiling.Data..ProfiledDbConnection.WrappedConnection
获取未经MiniProfile包装的原
IDbConnection
// ProfiledDbConnection 源码 public ProfiledDbConnection(DbConnection connection, IDbProfiler? profiler) { this._connection = connection ?? throw new ArgumentNullException(nameof (connection)); this._connection.StateChange += new StateChangeEventHandler(this.StateChangeHandler); if (profiler == null) return; this._profiler = profiler; } /// <summary> /// Gets the connection that this ProfiledDbConnection wraps. /// </summary> public DbConnection WrappedConnection => this._connection;
上篇介绍了如何使用MiniProfiler监控API性能,详见 如何在.NET 8.0中使用MiniProfiler
1. EntityFrameworkCore
EFCore直接引用相关nuget包:MiniProfiler.EntityFrameworkCore
Install-Package MiniProfiler.EntityFrameworkCore
修改MiniProfiler服务配置:
// ConfigureServices:
services.AddMiniProfiler( options =>
{
....
....
})
.AddEntityFramework();
2.其他ORM框架
MiniProfiler监控数据库查询,其实就是在原有的IDbConnection
上用 StackExchange.Profiling.Data.ProfiledDbConnection
包装了一层,使用包装后的IDbConnection进行数据库操作,MiniProfiler就可以监控到了。
知道原理后,我们开始上手改造IDbConnection
,下面的示例ORM使用轻量级框架Dapper
,数据库使用postgresql 14
。
Dapper原始查询:
await using var connection = new NpgsqlConnection(_connectionString)!;
connection.Open();
var query = await connection.QueryAsync<Employee>(@"select
*
FROM public.employee e
WHERE e.id=@id"
, new { id });
下面使用ProfiledDbConnection
:
await using var connection = new NpgsqlConnection(_connectionString)!;
connection = new StackExchange.Profiling.Data.ProfiledDbConnection(conn, MiniProfiler.Current);
connection.Open();
var query = await connection.QueryAsync<Employee>(@"select
*
FROM public.employee e
WHERE e.id=@id"
, new { id });