SharePoint 中的交叉方法处置模式 [英] Cross Method Dispose Patterns in SharePoint

查看:14
本文介绍了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 都需要处理,并且根据 Best Practices 文档中将这种情况称为交叉方法处置模式......只是他们没有就如何实现模式的处置部分给出任何实际建议.

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屋!

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