.NET 8.0中使用MiniProfiler监控数据库查询

·

1 min read

  1. 返回不同数据库类型的IDBConnection

  2. https://github.com/MiniProfiler/dotnet/issues/439

  3. 实践记录:Type.GetType()返回值为null的问题

  4. Type.GetType()跨程序集反射

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 });

效果: