Copied to clipboard

Flag this post as spam?

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


  • Niels Swimberghe 22 posts 105 karma points c-trib
    Oct 25, 2021 @ 15:35
    Niels Swimberghe
    0

    Should you always dispose of UmbracoContext?

    I recently moved from Umbraco 8 to Umbraco 9 and had to refactor my code to use the IUmbracoContextAccessor more often. This may be a dumb question, but I wanted to make sure.
    When getting an Umbraco context from IUmbracoContextAccessor, should we dispose of it or will it be handled elsewhere at the end of the request life cycle?

  • Corné Hoskam 80 posts 587 karma points MVP 2x c-trib
    Oct 28, 2021 @ 12:23
    Corné Hoskam
    1

    Hi Niels!

    Core services like the IUmbracoContextAccessor (but also things like the UmbracoHelper, IPublishedContentQuery, ...) are all based on an HttpRequest, and their lifetime is controlled by it. This also means that they will automatically be disposed of when the request itself ends! The same reason applies for why we cannot inject these services if we are not operating within a request!

    Hope this helped!

    Corné

  • Tom Weston 3 posts 73 karma points
    Apr 07, 2022 @ 10:32
    Tom Weston
    0

    Hey, I have a slightly related question, should we be disposing of context at all in this case?

    Reason I ask is I have a settings service that is constructor injecting the IUmbracoContextAccessor (as seen in https://github.com/jondjones/JonDJones.Umbraco.V9.StarterKit/blob/master/JonDJones.Core/Services/MenuService.cs )

    public class SiteSettingsService : ISiteSettingsService
    {
        private readonly IUmbracoContextAccessor _contextAccessor;
    
        public SiteSettingsService(IUmbracoContextAccessor contextAccessor)
        {
            _contextAccessor = contextAccessor;
        }
    
        public List<DisplayNameContent> GetHeaderMenu()
        {
            var siteSettings = GetSiteSettings();
            var headerMenuList = siteSettings.HeaderMenu.ToList();
            return headerMenuList;
        }
    
        public List<IPublishedContent> GetSomeOtherThings()
        {
            var siteSettings = GetSiteSettings();
            var welll = siteSettings.TEst;
            return welll.ToList();
        }
    
        private SiteSettings GetSiteSettings()
        {
            var context = _contextAccessor.GetRequiredUmbracoContext(); 
            return context.Content.GetAtRoot().DescendantsOrSelf<SiteSettings>().First();
        }
    }
    

    and this all works fine, but if I put add a using keyword on GetSiteSettings (like using var context = _contextAccessor.GetRequiredUmbracoContext(); ) then the call throws a ObjectDisposedException

    ...so I just don't add the using keyword and is fine, but should the context be IDisposable at all in this case?

Please Sign in or register to post replies

Write your reply to:

Draft