如何防止 mvc 站点地图提供程序的菜单 html 助手执行控制器、服务和存储库构造函数?

How to prevent controller, service and repository constructor executed by the mvc sitemap provider's menu html helper?

在_Layout.cshtml中,@Html.MvcSiteMap().Menu("viewname")在每个请求中导致了额外的2秒。我发现存储库的构造函数被执行了几次取决于菜单的计数所以我猜这可能是额外 2 秒的来源。

有没有办法防止在菜单呈现后执行构造函数?

我怀疑这是因为您正在使用 Security Trimming。为了确定每个 link 是否有访问权限,MVCSiteMapProvider 为每个操作创建并释放每个控制器的实例。避免这种情况的唯一方法是禁用安全修整。

启用安全修整后,不建议在构造函数中进行任何繁重的处理,因为这会对性能产生负面影响。您应该将任何处理(例如打开数据库连接)推迟到请求生命周期的后期,例如使用 Abstract Factory to create the connection and injecting the factory into your constructor instead of the dbcontext/connection object. See

也就是说,AuthorizeAttributeAclModule is not as efficient as it could be because when you have controllers with a lot of action methods, the same controller instance could be reused instead of creating one for each action method. You could make a custom AuthorizeAttributeAclModule and use the HttpContext.Items dictionary to request-cache each controller so they are reused instead of re-instatiated. You will need to do some refactoring to do it, though. The controller is created on line 235 and it is released on line 108。您需要确保在检查最后一个节点之后才调用发布。您可以通过创建一个 IActionFilter 来在操作完成后释放它们来做到这一点,但这意味着操作方法将需要了解与 [=10= 相同的请求缓存(在 HttpContext.Items 中) ].您只需要实现 OnActionExecuted 方法来从请求缓存中清除控制器。