SPSite 站点 = 新 SPSite(SPContext.Current.Web.Url) 与 SPContext.Current.Web.Site [英] SPSite site = new SPSite(SPContext.Current.Web.Url) vs SPContext.Current.Web.Site

查看:53
本文介绍了SPSite 站点 = 新 SPSite(SPContext.Current.Web.Url) 与 SPContext.Current.Web.Site的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么某些 SharePoint 示例使用

Why do some SharePoint examples use

using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
    ...
}

而不仅仅是简单的?

SPSite site = SPContext.Current.Web.Site;
...

更新

我想我已经将问题缩小到以下几点:

I think I have narrowed the question down to the following:

似乎我不应该直接使用 SPContent.Current,除非我确定我的代码在 SharePoint 中运行.但什么时候不是真的?

It seems that I should not use SPContent.Current directly, unless I am certain, that my code runs inside SharePoint. But when would that not be true?

推荐答案

查看 在 SharePoint 2010 中处理对象 来自 Microsoft,但是有 反对意见.

Take a look at the best practices documentation on disposing objects in SharePoint 2010 from Microsoft, however there are opposing views.

SharePoint 项目有几个关键要点:

There are a few key takeaways for SharePoint projects:

  • 始终处理您的 SPWeb/SPSite 对象 --> 内存泄漏
  • 当您确定代码在 SharePoint 上下文中运行时,请使用 SPContext.Current...
    • 单元测试意味着没有 Sharepoint 上下文
    • 外部实用程序意味着没有 Sharepoint 上下文
    • Powershell 意味着没有 SharePoint 上下文(例如,使用功能接收器激活功能可能会失败)
    • Always dispose your SPWeb / SPSite objects --> memory leaks
    • Make use of SPContext.Current... when you are sure your code is running in a SharePoint context
      • Unit Tests mean no Sharepoint context
      • External utilities mean no Sharepoint context
      • Powershell means no SharePoint context (e.g. activating a feature with feature receiver might fail)

      您可能有 与您的多个 SP.. 对象的一致性问题.

      最后 SPSite site = SPContext.Current.Web.Site; 在某些情况下很好,但您无法控制这个 site 对象 - 这可能成为问题.如果您选择 new SPSite(...),您将始终拥有您的 SPSite,而不是 SharePoint 为您创建和管理的内容.

      In the end SPSite site = SPContext.Current.Web.Site; is fine in some instances, but you do not have control over this site object - that might be the problem. If you go for new SPSite(...) you will always have your SPSite and not something SharePoint created and managed for you.

      就我个人而言,我几乎总是采用 using 结构,以便之后正确处理所有对象.或者我使用 SPContext.Current.Web 而不处理.

      Personally I almost always go for the using structure so all objects are disposed properly afterwards. Alternatively I use SPContext.Current.Web without disposing.

      这篇关于SPSite 站点 = 新 SPSite(SPContext.Current.Web.Url) 与 SPContext.Current.Web.Site的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆