SharePoint中的跨方法处置模式 [英] Cross Method Dispose Patterns in SharePoint
问题描述
我编写了一个类,可以对SharePoint网站的内容进行各种修改。在该类中,我实现了一个懒惰的可解析属性
I've written a class that does various modification to the contents of a SharePoint site. Inside that class, I've implemented a lazy resolved property
private SPWeb rootSite
{
get
{
if ( _site == null )
{
SPSite site = new SPSite( _url );
_site = site.OpenWeb();
}
return _site;
}
}
需要处置SPSite和SPWeb,根据最佳做法文档,这种情况称为交叉方法处置模式...只是他们没有对如何实现模式的处理部分给出任何实际建议。
Both the SPSite and the SPWeb need to be disposed, and according to the Best Practices document this situation is called a Cross Method Dispose Pattern... only they don't give any actual suggestion on how to implement the dispose part of the pattern.
我选择让我的课程实现IDisposable(将网站和网站放置在此处),并让调用者通过 using 子句访问它。是按照最佳实践,还是我应该以不同的方式处理问题?
I opted to have my class implement IDisposable (disposing the site and web there), and have the caller access it through a using clause. Would that be according to "best practices", or should I have handled the problem differently?
请注意,我来自严格的引用计数背景,因此如果我对垃圾处理的看法有些偏离,请纠正我。
推荐答案
我认为交叉方法处理模式是最佳实践中最差的。最好总是使用依赖注入为类提供SPSite或SPWeb引用,以供类使用,也许可以通过构造函数。这样一来,您的班级就不用担心处置,它只使用SharePoint上下文。
I consider the "Cross Method Dispose Pattern" to be the worst of the "Best Practices". It is almost always better to use dependency injection to provide an SPSite or SPWeb reference for your class to use, perhaps through the constructor. That way your class has no disposal concerns, it just consumes the SharePoint context.
也就是说,如果您希望继续使用此模式,请实施 IDisposable
是正确的方法。但是,您应该跟踪并处置 SPSite
而不是 SPWeb
。我可以这样实现:
That said, if you wish to proceed with this pattern, implementing IDisposable
is the correct approach. However, you should track and dispose the SPSite
rather than the SPWeb
. I might implement it like this:
public class MyClass : IDisposable
{
private string _url;
private SPSite _site;
private SPWeb _web;
private SPSite RootSite
{
get
{
if ( _site == null )
{
_site = new SPSite( _url );
}
return _site;
}
}
private SPWeb RootWeb
{
get
{
if ( _web == null )
{
_web = RootSite.OpenWeb();
}
return _web;
}
}
void IDisposable.Dispose()
{
if (null != _site)
{
_site.Dispose();
}
}
}
请注意, _web
将通过调用 _site.Dispose()
自动处理。
Note that _web
will be automatically disposed by the call to _site.Dispose()
.
这篇关于SharePoint中的跨方法处置模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!