1
\$\begingroup\$

How will this example affect the using implementation in GetSite?

public abstract class SPSiteBase
{
 protected abstract string Url { get; set; }
 public abstract SPSite GetSite(string url = null);
}
public class SPSiteFactory : SPSiteBase
{
 protected override sealed string Url { get; set; }
 public override SPSite GetSite(string url = null)
 {
 using (SPSite site = new SPSite(string.IsNullOrEmpty(url) ? Url : url))
 {
 return site;
 }
 }
 public SPSiteFactory() { }
 public SPSiteFactory(string url)
 {
 Url = url;
 }
}

I call it like this

SPSiteFactory siteFactory = new SPSiteFactory("http://portalurl/");
SPSite site = siteFactory.GetSite();

I've noticed that the code steps out of the using after I run the siteFactory.GetSite() method but will the site ever be disposed?

asked Jan 3, 2014 at 19:03
\$\endgroup\$
1
  • \$\begingroup\$ using { return } is the same as try { return }—it won't magically handle errors the calling code. Thus using will dispose right away. \$\endgroup\$ Commented Jan 3, 2014 at 20:10

1 Answer 1

6
\$\begingroup\$

No, you can't use a factory to dispose your objects, your code is creating and immediately disposing the SPSite as soon as it steps out of your method.

public override SPSite GetSite(string url = null)
{
 return new SPSite(string.IsNullOrEmpty(url) ? Url : url))
}

Have the disposing be handled by the calling code. You can't handle the disposing from a factory method.

If you want to check it out, build your own disposable type, put a breakpoint in the Dispose method and check for yourself.

answered Jan 3, 2014 at 19:14
\$\endgroup\$
3
  • \$\begingroup\$ That would make returning disposable variables by using using in a factory pattern to an antipattern, that's all I needed, thanks! \$\endgroup\$ Commented Jan 3, 2014 at 22:43
  • 2
    \$\begingroup\$ @EricHerlitz I wouldn't say it's an anti-pattern. Anti-pattern is something that works, but is bad design. This code simply doesn't work, it returns an object that's already disposed. \$\endgroup\$ Commented Jan 5, 2014 at 22:59
  • \$\begingroup\$ The instance of site still works but the site in the factory is disposed \$\endgroup\$ Commented Jan 6, 2014 at 8:12

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.