Copied to clipboard

Flag this post as spam?

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

  • Chad 18 posts 119 karma points
    May 21, 2019 @ 18:49

    UmbracoContextFactory vs UmbracoContext

    When is it appropriate to inject the UmbracoContext and when would it be appropriate to inject the UmbracoContextFactory?

    I am looking for documentation on the intended use case for each of these classes. For example, when writing a service that gets content data for a surface controller, what would be the correct class to inject?

  • Marc Goodson 1178 posts 7893 karma points MVP 5x c-trib
    May 22, 2019 @ 22:28
    Marc Goodson

    Hi Chad

    There is some work in progress documentation taking shape here that might help:

    Essentially in some places in Umbraco where you might want to inject a custom service of your own creation, the UmbracoContext is not guaranteed to exist, and you would get a boot error - eg a Component or ContentFinder - here therefore if you need to access the Umbraco published Cache you would inject the UmbracoContextFactory and wrap a call to EnsureUmbracoContext in a using statement, to get reference to the content cache - there is an example in the link above.

    If you are inheriting from one of Umbraco's special base classes, eg RenderMvcController, SurfaceController, UmbracoApiController

    then you already have access to the UmbracoContext, via the 'UmbracoContext' property that they all expose.


    using System.Web.Mvc;
    using Umbraco.Web.Mvc;
    namespace Umbraco8.Controllers
        public class TestSurfaceController : SurfaceController
            // GET: TestSurface
            public ActionResult Index()
                var somePublishedContent = UmbracoContext.ContentCache.GetById(1234);
                return View(somePublishedContent);

    (the injection is done for you!)



Please Sign in or register to post replies

Write your reply to: