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 122 karma points
    May 21, 2019 @ 18:49
    Chad
    1

    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 2155 posts 14406 karma points MVP 9x c-trib
    May 22, 2019 @ 22:28
    Marc Goodson
    1

    Hi Chad

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

    https://github.com/umbraco/UmbracoDocs/compare/v8/ServicesPattern?short_path=cf2726d#diff-cf2726d2ea2b6f60e0225ce051876a55

    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.

    eg

    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!)

    regards

    marc

Please Sign in or register to post replies

Write your reply to:

Draft