Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Jason Elkin 38 posts 351 karma points MVP 3x c-trib
    Sep 10, 2018 @ 10:34
    Jason Elkin
    0

    Should I dispose of the UmbracoContext I create with UmbracoContext.EnsureContext ?

    I'm using the following code (From https://gist.github.com/sniffdk/7600822) that spits out an UmbracoContext for a few background tasks. They are not always backgrounded, so UmbracoContext.Current is sometimes available.

    public static UmbracoContext GetOrCreateContext()
    {
        if (UmbracoContext.Current != null)
        {
            return UmbracoContext.Current;
        }
    
        var httpContext = new HttpContextWrapper(HttpContext.Current ?? new HttpContext(new SimpleWorkerRequest("temp.aspx", "", new StringWriter())));
    
        return UmbracoContext.EnsureContext(
            httpContext,
            ApplicationContext.Current,
            new WebSecurity(httpContext, ApplicationContext.Current),
            UmbracoConfig.For.UmbracoSettings(),
            UrlProviderResolver.Current.Providers,
            false);
    }
    

    I notice that UmbracoContext is IDisposable. My instinct is that if I have created something that is disposable then I should dispose of it, is that a correct assumption?

    I'm also guessing that I shouldn't dispose of UmbracoContext.Current so I've put this in place, is it a sensible approach?

        public static void CompleteActionWithUmbracoContext(Action<UmbracoContext> action)
        {
            if (UmbracoContext.Current != null)
            {
                action(UmbracoContext.Current);
            }
            else
            {
                using (var ctx = GetOrCreateContext())
                {
                    action(ctx);
                }
            }
        }
    
  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies