开发者

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

Given this snippet of code

public abstract class Foo
{
    private static Sql开发者_高级运维Connection _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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜