Copied to clipboard

Flag this post as spam?

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


  • Elliott Brown 41 posts 211 karma points
    Aug 23, 2021 @ 09:21
    Elliott Brown
    0

    Umbraco 8 Inject UmbracoHelper for global use

    Hi, I'm in the process of upgrading from V7 to V8 and I'm stuck on how to inject UmbracoHelper as service for global use.

    My C# skills/ knowledge are/is a work in progress so if there's my use of 'inject' is incorrect, please don't kill me :) . I hope I'm able to learn something from the answer to this post.

    In our current installation we very effectively utilize

    private static UmbracoHelper Helper
        {
            get
            {
                return new UmbracoHelper(UmbracoContext.Current);
            }
        }
    

    As you know, this 'setup' is not available in V8.

    However, within each method that I call this helper I can add a 'local' instance of

    UmbracoHelper helper = Umbraco.Web.Composing.Current.UmbracoHelper;
    

    and it will work. But this doesn't feel like a good solution!

    is there a way of achieving the same as we did in V7 and exposing 'helper' globally - or at least within the controller?

    Thanks!

  • Elliott Brown 41 posts 211 karma points
    Aug 23, 2021 @ 09:25
    Elliott Brown
    100

    EDIT: So I found my own answer!

    This:

    private static UmbracoHelper Helper
    {
        get
        {
            return new UmbracoHelper(UmbracoContext.Current);
        }
    }
    

    can be replaced with:

    private static UmbracoHelper Helper
        {
            get
            {
                return Umbraco.Web.Composing.Current.UmbracoHelper;
            }
        }
    
  • Nik 1614 posts 7260 karma points MVP 7x c-trib
    Aug 23, 2021 @ 11:41
    Nik
    1

    Hi Elliot,

    Injecting/using the UmbracoHelper outside of a web request is not recommended. If you need to access things like content etc on things like background threads, you are better off injecting IUmbracoContextFactory, and the other interfaces that the UmbracoHelper wraps up.

    If you find you start getting things not working as expected, or odd errors occurring this could be the reason, just so you are aware.

    Thanks

    Nik

Please Sign in or register to post replies

Write your reply to:

Draft