Getting UmbracoHelper in class
# help-with-umbraco
t
Hi all I'm using the below code in Umbraco 13 custom class public IPublishedContent GetProductById(int id) { var accessor = StaticServiceProvider.Instance.GetRequiredService(); if (accessor.TryGetUmbracoHelper(out var umbracoHelper)) { return umbracoHelper.Content(id); } return null; } This returns the error InvalidOperationException wasn't able to get an UmbracoContext. When searching on this error, most lead me to Umbraco 9 bugs so wondering if I'm missing something?
d
Hi there! You should not need to rely on the
StaticServiceProvider
class and I would highly recommend against using it. The
UmbracoHelper
can only be fetched in a thread that is handling a request for an Umbraco content page. Outside that, you don't have the umbraco helper available. Read more about dependency injection here: https://docs.umbraco.com/umbraco-cms/v/13.latest-lts/reference/using-ioc Read more about umbraco helper here: https://docs.umbraco.com/umbraco-cms/v/13.latest-lts/reference/querying/umbracohelper
t
Hi if I have a few controllers using the above method from my custom class then there is no way to reuse it? I have to inject it into ALL the controllers?
d
injecting IS reusing. You register your class once inside dependency injection and your constructors automatically receive your class
t
A little confused.... I have my custom class registered. Everything works until I call the method above. There are other methods in the class too which work but it's only when using the UmbracoHelper that I receive an error
d
Are you still using
StaticServiceProvider
in your class? If so, you should instead add
IUmbracoHelperAccessor
in the constructor of your class and rely on that instead.
Copy code
c#
public class MyCustomClass
{
    private readonly IUmbracoHelperAccessor _umbracoHelperAccessor;
    public MyCustomClass(IUmbracoHelperAccessor umbracoHelperAccessor)
    {
        _umbracoHelperAccessor = umbracoHelperAccessor;
    }

    public void MyCustomMethod()
    {
        var umbracoHelper = _umbracoHelperAccessor.GetRequiredUmbracoHelper();
        // ... use the umbraco helper
    }
}
t
Thanks that did the trick!
37 Views