How to pass a mvc-mini-profiler connection to a base class from MVC3

asp.net-mvc-3 dapper mvc-mini-profiler

Question

Given this snippet of code

public abstract class Foo
{
    private static SqlConnection _sqlConnection;

    protected SqlConnection GetOpenConnection()
    {
        if (_sqlConnection == null)
        {
            _sqlConnection = new SqlConnection("connection string");
        }
        return _sqlConnection;
    }

    protected abstract void Execute();
}

public class FooImpl : Foo
{

    protected override void Execute()
    {
        var myConn = GetOpenConnection();
        var dog = myConn.Query<dynamic>("select 'dog' Animal");
        var first = dog.First();

        string animalType = first.Animal;
        // more stuff here
    }
}

How would you wrap the connection in a profiled connection if you don't have access to the connection creation process? Rewrite the code in the super class and wrap it there? This would involve changing hundreds of classes that inherit from the base. I'd prefer a way to change the base class, with as little changes necessary to the supers.

Thank you, Stephen

Accepted Answer

Well after a bit of trial and error I compromised and added a ref to MvcMiniProfiler in the base library and changed the connection code a bit.

    protected DbConnection GetOpenConnection()
    {
        if (_connection == null)
        {
            _connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connection string "].ConnectionString);
            _connection.Open();
        }
        return MvcMiniProfiler.Data.ProfiledDbConnection.Get(_connection, MiniProfiler.Current); 
    }

    private static SqlConnection _connection;

This works for both hosting in the MVC project (for profiling purposes, where we don't have that capability (QA/Prod Databases)) and WPF/Windows Service




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why