Integrate MiniProfiler in Dapper

Introduction

MiniProfiler is a useful tool for track the website performance and bugs, you can see how many times spent in each page, which queries are run, and any other custom timings you want to add, MiniProfiler helps you debug issues and optimize performance.

MiniProfier has support many of kinds ORM framework, you can easy to find how to integrate in it’s home page. But for there is no detail information for integrate with Dapper.

Dapper is a simple object mapper for .NET and own the title of King of Micro ORM in terms of speed and is virtually as fast as using a raw ADO.NET data reader. An ORM is an Object Relational Mapper, which is responsible for mapping between database and programming language.

So for Dapper , we can use DbConnection for integrate with MiniProfiler to profile the SQL query.

Using the code

We will create a common function for create the DbConnection as below:

protected static DbConnection GetOpenConnection(bool mars = false)
{
    try
    {
        if (string.IsNullOrEmpty(ConnectionString))
        {
            throw new Exception("There is no connection!");
        }

        var cs = ConnectionString;
        if (mars)
        {
            var scsb = new SqlConnectionStringBuilder(cs)
            {
                MultipleActiveResultSets = true
            };
            cs = scsb.ConnectionString;
        }
        connection = new SqlConnection(cs);
        connection.Open();

        return connection;
    }
    catch(Exception ex)
    {
        throw ex;
    }
}

The above code will return an connection for Dapper, so that you can use it directly.

If you want to profile the SQL with MiniProfiler, we need to add the below code:

var conn = new StackExchange.Profiling.Data.ProfiledDbConnection(connection, MiniProfiler.Current);
conn.Open();

It will be create the connection via MiniProfiler at this time, so the full code should be look like below:

protected static DbConnection GetOpenConnection(bool mars = false)
{
    try
    {
        if (string.IsNullOrEmpty(ConnectionString))
        {
            throw new Exception("There is no connection!");
        }

        var cs = ConnectionString;
        if (mars)
        {
            var scsb = new SqlConnectionStringBuilder(cs)
            {
                MultipleActiveResultSets = true
            };
            cs = scsb.ConnectionString;
        }
        connection = new SqlConnection(cs);
        
        //return the connection create by MiniProfiler
        var conn = new StackExchange.Profiling.Data.ProfiledDbConnection(connection, MiniProfiler.Current);
        conn.Open();

        return conn;
    }
    catch(Exception ex)
    {
        throw ex;
    }
}

36,729 total views, 17 views today

Do you like this post?
  • Fascinated
  • Happy
  • Sad
  • Angry
  • Bored
  • Afraid

winson

Leave a Reply

coder-blog-1
shares