MiniProfiler工具介绍

    MiniProfiler是一款针对.NET, Ruby, Go and Node.js的性能分析的轻量级程序。可以对一个页面本身,及该页面通过直接引用、Ajax、Iframe形式访问的其它页面进行监控,监控内容包括数据库内容,并可以显示数据库访问的SQL(支持EF、EF CodeFirst等 )。并且以很友好的方式展现在页面上。

    MiniProfiler官网:http://miniprofiler.com/

    MiniProfiler的一个特别有用的功能是它与数据库框架的集成。除了.NET原生的 DbConnection类,MiniProfiler还内置了对实体框架(Entity Framework)以及LINQ to SQL、RavenDb和MongoDB的支持。任何执行的Step都会包括当时查询的次数和所花费的时间。为了检测常见的错误,如N+1反模式,profiler将检测仅有参数值存在差异的多个查询。

    MiniProfiler是以Apache License V2.0协议发布的,你可以在NuGet找到。

  过去一直使用Sqlserver Profiler但是发现实在是太痛苦了,你不得不进行新建、过滤、清除、关闭等操作,而且过滤筛选往往比较难以控制。后来发现MiniProfiler工具非常好用。

  同类监控工具有NanoProfiler下载地址:https://github.com/ef-labs/nanoprofiler/issues/1

Demo演示

Demo开发环境

  • Win10
  • VS2013

准备工作

新建MVC项目WebAppEF,使用Northwind数据库。

1、先安装MiniProfiler

2、安装MiniProfiler.MVC4

3、安装MiniProfiler.EF

4、修改Global.asax文件

我这里只需要在开发环境使用SQL性能监控,所以使用了#if DEBUG,因为生产环境,我们一般是采用release模式。同时,MiniProfiler还支持授权,这里不做介绍。

复制代码
using StackExchange.Profiling;
using StackExchange.Profiling.EntityFramework6;
using System;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace WebAppEF
{
publicclassMvcApplication : System.Web.HttpApplication
    {
protectedvoid Application_Start()
        {
#if DEBUG
MiniProfilerEF6.Initialize();
#endif
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
protectedvoid Application_BeginRequest(Object source, EventArgs e)
        {
#if DEBUG
MiniProfiler.Start();
#endif
        }
protectedvoid Application_EndRequest()
        {
#if DEBUG
MiniProfiler.Stop();
#endif
        }
    }
}
复制代码

5、在你的布局页(_Layout)中,比如以下这种结构,修改_Layout.cshtml

@using StackExchange.Profiling;
<head>
 ..
</head>
<body>
  ...
  @MiniProfiler.RenderIncludes()
</body>
6、修改配置文件Web.config
<system.webServer>
<handlers>
<add name="MiniProfiler" path="mini-profiler-resources/*" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode"/>
</handlers>
</system.webServer>

7、添加控制器测试代码
复制代码
        public ActionResult Index()
        {
            // create the entity object
            using (NorthwindEntities mobjentity = new NorthwindEntities())
            {
                ViewBag.SelectCustomer = mobjentity.Customers.Select(x => x.City == "Delhi").ToList();
            }

            var profiler = MiniProfiler.Current;
            using (profiler.Step("查询Customers的数据"))
            {
                using (NorthwindEntities entity = new NorthwindEntities())
                {
                    ViewBag.data = entity.Customers.ToList();
                }
            }
            return View();
        }
复制代码
8、按F5调试运行

说明:标记为duplicate的部分,代表在一次请求当中,重复执行了查询,可以进行优化。通过Step可以对独立的sql块进行标记。

常见错误

1、The Entity Framework was already using a DbConfiguration instance before an attempt was made to add an 'Loaded' event handler. 'Loaded' event handlers can only be added as part of application start up before the Entity Framework is used. See http://go.microsoft.com/fwlink/?LinkId=260883 for more information.

分析:错误提示的大意是在试图为DbConfiguration 实例加Loaded事件之前已经在其它地方使用了这个实例了

解决方案:把MiniProfiler.EF6.Initialize()在放在Database.SetInitializer<WebAppEF.Models.NorthwindEntities>(null); 之前。

2、Could not load file or assembly 'MiniProfiler, Version=3.0.11.0, Culture=neutral, PublicKeyToken=b44f9351044011a3' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

分析:找不到MiniProfiler程序集或者它的依赖项。程序集定义和引用不匹配。

解决方案:查看Web.config中是否存在如下配置节点

<dependentAssembly>
<assemblyIdentityname="MiniProfiler"publicKeyToken="b44f9351044011a3"culture="neutral" />
<bindingRedirectoldVersion="0.0.0.0-3.2.0.157"newVersion="3.2.0.157" />
</dependentAssembly>

如果不存在则添加,如果存在,则检查MiniProfiler版本号和packages.config中的版本号是否一致,如果不一致就要对版本号进行修改。

参考:

使用MiniProfiler调试ASP.NET MVC网站性能

采用MiniProfiler监控EF与.NET MVC项目(Entity Framework 延伸系列1)

posted @   邹琼俊  阅读(12005)  评论(8编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
-->
点击右上角即可分享
微信分享提示