IUmbracoContextAccessor

In ASP.NET Core versions of Umbraco, the IUmbracoContextAccessor interface represents an injectable service that allows getting the current IUmbracoContext instance - if one is available. The IUmbracoContextAccessor describes a TryGetUmbracoContext method as well as a GetRequiredUmbracoContext extension method.

The TryGetUmbracoContext generally works well when you need to check whether an IUmbracoContext is currently available, and the GetRequiredUmbracoContext extension method will get the current IUmbracoContext - or throw an exception if not available.

We have found ourselves in situations where it's not super important whether an IUmbracoContext is available - eg. because we have addtional checks further down our code. For this, we've introduced a GetUmbracoContext extension method that returns the IUmbracoContext if available, or null if not.

In the example below, we have a custom service that injects IUmbracoContextAccessor, and then uses our GetUmbracoContext as part of a method chain for finding the news list from the ID of it's parent site:

using Skybrud.Essentials.Umbraco;
using Umbraco.Cms.Core.Models.PublishedContent;
using Umbraco.Cms.Core.Web;

public class MyService {

    private readonly IUmbracoContextAccessor _umbracoContextAccessor;

    public MyService(IUmbracoContextAccessor umbracoContextAccessor) {
        _umbracoContextAccessor = umbracoContextAccessor;
    }

    public IPublishedContent? GetNewsList(int siteId) {
        return _umbracoContextAccessor
            .GetUmbracoContext()?.Content?
            .GetById(siteId)?
            .FirstChildOfType("newsList");
    }

}