Cross Method Dispose Patterns in SharePoint

佐手、 提交于 2019-12-03 16:25:17

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.

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();
        }
    }
}

Note that _web will be automatically disposed by the call to _site.Dispose().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!