Copied to clipboard

Flag this post as spam?

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


  • nickornotto 403 posts 907 karma points
    May 18, 2022 @ 16:18
    nickornotto
    0

    How to get UmbracoHelper in a custom attribute without DI?

    I am trying to create a custom attribute that uses umbraco dictionary value.

    I do not know how to get the UmbracoHelper instance as I don't thunk a custom attribute supports dependency injection.

    Any thoughts how to get UmbracoHelper in other way than DI?

    This is what I have:

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
    public sealed class UmbracoDisplayAttribute : DisplayNameAttribute
    {
        private readonly UmbracoHelper _umbracoHelper; // <- this value is missing
    
        // This is a positional argument
        public UmbracoDisplayAttribute(string dictionaryKey)
            : base(dictionaryKey)
        {
        }
    
        public override string DisplayName
        {
            get
            {
                return _umbracoHelper != null ? _umbracoHelper.GetDictionaryValue(base.DisplayName) : string.Empty;
            }
        }
    }
    
  • nickornotto 403 posts 907 karma points
    May 18, 2022 @ 22:59
    nickornotto
    0

    Is there any way of getting UmbracoHelper without DI in Umbraco 9?

  • Dave Woestenborghs 3504 posts 12135 karma points MVP 9x admin c-trib
    May 19, 2022 @ 07:13
    Dave Woestenborghs
    102

    Hi nickornotto,

    Dependency injection in attributes is not possible. This not a Umbraco thing but .NET thing.

    You could retrieve the dependency in your attribute using the service locator pattern.

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
    public sealed class UmbracoDisplayAttribute : DisplayNameAttribute
    {
        // This is a positional argument
        public UmbracoDisplayAttribute(string dictionaryKey)
            : base(dictionaryKey)
        {
        }
    
        public override string DisplayName
        {
            get
            {
    var umbracoHelper =  new HttpContextAccessor().HttpContext.RequestServices.GetService<UmbracoHelper>();
                return umbracoHelper != null ? umbracoHelper.GetDictionaryValue(base.DisplayName) : string.Empty;
            }
        }
    }
    
  • nickornotto 403 posts 907 karma points
    May 19, 2022 @ 15:01
    nickornotto
    0

    Bril, thank you!

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies