Copied to clipboard

Flag this post as spam?

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


  • nickornotto 397 posts 900 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 397 posts 900 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 12133 karma points MVP 8x admin c-trib
    May 19, 2022 @ 07:13
    Dave Woestenborghs
    101

    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 397 posts 900 karma points
    May 19, 2022 @ 15:01
    nickornotto
    0

    Bril, thank you!

Please Sign in or register to post replies

Write your reply to:

Draft