如何将mvc-mini-profiler连接从MVC3传递给基类

时间:2011-08-09 12:27:05

标签: asp.net-mvc-3 mvc-mini-profiler dapper

给出这段代码

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

如果您无权访问连接创建过程,如何在配置连接中包装连接?重写超类中的代码并将其包装在那里?这将涉及更改从基础继承的数百个类。我更喜欢一种改变基类的方法,只需要对超级组织进行必要的修改。

谢谢你, 斯蒂芬

1 个答案:

答案 0 :(得分:3)

经过一些试验和错误后,我妥协了并在基础库中添加了一个引用MvcMiniProfiler并更改了连接代码。

    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;

这适用于MVC项目中的托管(用于分析目的,我们没有该功能(QA / Prod数据库))和WPF / Windows服务