使用 MvcMiniProfiler 监控EF 4.1 with MySQL Provider

本文有2个不怎么相关的话题,一是用MVCMiniProfiler 监控EF4.1,另一个则是为MvcMiniProfiler提供MySQL Provider的支持。

需要在Web.config中添加system.data的节点

   1: <remove invariant="MvcMiniProfiler.Data.ProfiledDbProvider" />
   2: <add name="MvcMiniProfiler.Data.ProfiledDbProvider" invariant="MvcMiniProfiler.Data.ProfiledDbProvider"
   3:         description="MvcMiniProfiler.Data.ProfiledDbProvider"
   4:         type="MvcMiniProfiler.Data.ProfiledDbProviderFactory, MvcMiniProfiler, Version=1.7.0.0, Culture=neutral, PublicKeyToken=b44f9351044011a3" />

另外在Application_Start设置Database.DefaultConnectionFactory即可

   1: var factory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0"); 
   2: var profiled = new MvcMiniProfiler.Data.ProfiledDbConnectionFactory(factory);
   3: Database.DefaultConnectionFactory = profiled;

当然,使用MySQL的话需要使用MySQL的ConnectionFactory,但是MySQL没有为我们提供,所以我们就自己写一下

   1: class MySqlConnectionFactory : IDbConnectionFactory
   2:         {
   3:             public DbConnection CreateConnection(string nameOrConnectionString)
   4:             {
   5:                 using (MiniProfiler.Current.Step("创建Connection:" + nameOrConnectionString))
   6:                 {
   7:                     var connStr = ConfigurationManager.ConnectionStrings[nameOrConnectionString];
   8:                     return new MySqlConnection(connStr.ConnectionString);
   9:                 }
  10:             }
  11:         }

然后使用MySqlConnectionFactory来注册

   1: var factory = new MySqlConnectionFactory();
   2: var profiled = new ProfiledDbConnectionFactory(factory);
   3: Database.DefaultConnectionFactory = profiled;

但是有很多时候使用EF4.1这样做并不会生效我们可能还要为DbContext包装一个基类来实现如下功能

   1: abstract public class BaseDbContext :DbContext
   2:    {
   3:        protected BaseDbContext(string nameOrConnectionString)
   4:            : base(GetConnection(nameOrConnectionString),true)
   5:        {
   6:           
   7:        }
   8:  
   9:        private static DbConnection GetConnection(string nameOrConnectionString)
  10:        {
  11:            if( Database.DefaultConnectionFactory is SqlConnectionFactory)
  12:            {//这个判断是为了解决未使用MySqlConnectionFactory时自动使用SQLServer的问题
  13:                var connStr = ConfigurationManager.ConnectionStrings[nameOrConnectionString];
  14:                return new MySqlConnection(connStr.ConnectionString);
  15:            }
  16:            return Database.DefaultConnectionFactory.CreateConnection(nameOrConnectionString);
  17:        }
  18: }
posted @ 2011-08-01 19:46  重典  阅读(3548)  评论(4编辑  收藏  举报