Porting extension methods to Umbraco 10 - how do I...
# help-with-umbraco
z
Some old V7 code I have looks like this:
Copy code
public static class IPublishedContentExtensions
{
    public static string TitleOrPageName(this IPublishedContent content, string titleAlias = "navigationLabel")
    {
        return content.HasValue(titleAlias) ? content.GetPropertyValue<string>(titleAlias) : content.Name;
    }
    public static int GetYearFromDateOrLatest(this IPublishedContent content, string fieldAlias)
    {
        return content.HasValue(fieldAlias) ? content.GetPropertyValue<DateTime>(fieldAlias).Year : DateTime.Now.Year;
    }
}
I obviously need to do something like this for V10:
Copy code
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Models.PublishedContent;
using Umbraco.Extensions;

namespace MyApplication.Web.Extensions;

public static string TitleOrPageName(this IPublishedContent content, string titleAlias = "navigationLabel")
{
    return content.HasValue(alias: titleAlias) ? content.Value<string>(_publishedValueFallback, titleAlias) : content.Name;
}
As this is a static class I cannot inject _publishedValueFallback. I am aware Umbraco.Extensions should have a method that doesn't need the interface but it doens't seem to be available here. What way should I be doing this?
r
There's a couple of options that I'd consider non-hacky: 1. Pass the IPublishedValueFallback into the static method as a parameter. 2. Convert the static class into a non-static service or helper class that can use DI, and inject that where you were using the extension before. This makes the code easier to test as well, if you do that in the future. Or if you're willing to go the (imo) hacky route, Umbraco.Extensions does indeed use a thing to get the interface:
Copy code
csharp
private static IPublishedValueFallback PublishedValueFallback { get; } =
    StaticServiceProvider.Instance.GetRequiredService<IPublishedValueFallback>();
I'm not a fan of that personally, but it should work.
z
thanks. I think I'll go for the helper method. Is there a reason the "nice" methods of Umbraco.Extensions don't work in this scenario? I've found they only seem to be available within Views.
r
Honestly not sure on that one
z
no worries, thanks.
k
We used option 1 when upgrading.
z
Upgrading sure is proving to be a pain. 😦
2 Views