我正在尝试MVCMiniProfiler使用PetaPoco
我正在尝试在创建PetaPoco数据库时设置连接,但遇到问题(connectionClosed)
public class DbHelper
{
static Database _CurrentDb = null;
public static Database CurrentDb()
{
if (_CurrentDb == null)
{
string connstr = ConfigurationManager.ConnectionStrings["MainConnectionString"].ConnectionString;
var conn = ProfiledDbConnection.Get(new SqlConnection(connstr));
_CurrentDb = new PetaPoco.Database(conn);
}
return _CurrentDb;
}
}
我已阅读此项目https://github.com/toptensoftware/PetaPoco/issues/44,但可以让它发挥作用
这样做的正确方法是什么?
解决方案由Gareth Elms提供:
public class DbHelper
{
static Database _CurrentDb = null;
public static Database CurrentDb()
{
if (_CurrentDb == null)
{
_CurrentDb = new DatabaseWithMVCMiniProfiler("MainConnectionString");
}
return _CurrentDb;
}
}
public class DatabaseWithMVCMiniProfiler : PetaPoco.Database
{
public DatabaseWithMVCMiniProfiler(IDbConnection connection) : base(connection) { }
public DatabaseWithMVCMiniProfiler(string connectionStringName) : base(connectionStringName) { }
public DatabaseWithMVCMiniProfiler(string connectionString, string providerName) : base(connectionString, providerName) { }
public DatabaseWithMVCMiniProfiler(string connectionString, DbProviderFactory dbProviderFactory) : base(connectionString, dbProviderFactory) { }
public override IDbConnection OnConnectionOpened( IDbConnection connection)
{
// wrap the connection with a profiling connection that tracks timings
return MvcMiniProfiler.Data.ProfiledDbConnection.Get( connection as DbConnection, MiniProfiler.Current);
}
}
答案 0 :(得分:3)
我想知道这是不是因为它是一个静态类。在请求之后连接会自动关闭可能会有些奇怪,而petapoco的_sharedConnectionDepth计数器不知道它。我使用你的代码轻松地复制了这个。在github https://github.com/GarethElms/PetaPoco----A-simple-web-app查看我的示例petapoco应用程序,我所做的只是在基本控制器中实例化数据库
答案 1 :(得分:1)
正如Schotime所提到的,每个请求对于mvc应用程序来说是最好的。 这是我使用Ninject的原因
private static void RegisterServices(IKernel kernel)
{
#if DEBUG
kernel.Bind<IDatabase>().To<DebugDatabase>()
.InRequestScope()
.WithConstructorArgument("connectionStringName", "DebugCnnString");
#else
kernel.Bind<IDatabase>().To<ReleaseDatabase>()
.InRequestScope()
.WithConstructorArgument("connectionStringName", "ReleaseCnnString");
#endif
}
public class DebugDatabase : PetaPoco.Database
{
public DebugDatabase(string connectionStringName) : base(connectionStringName) { }
public override IDbConnection OnConnectionOpened(IDbConnection connection)
{
// wrap the connection with a profiling connection
return new ProfiledDbConnection(connection as DbConnection, MiniProfiler.Current);
}
}
public class ReleaseDatabase : PetaPoco.Database
{
public ReleaseDatabase(string connectionStringName) : base(connectionStringName) { }
// ... some stuff
}