Copied to clipboard

Flag this post as spam?

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


  • Bo Jacobsen 593 posts 2389 karma points
    Jan 07, 2020 @ 10:58
    Bo Jacobsen
    0

    How to use UmbracoHelper MemberHasAccess in a custom service?

    Hi all.

    How would i inject the UmbracoHelper into a custom service in order to use the MemberHasAccess method?

    public class MyService : IMyService
    {
        public IUmbracoContextFactory Context { get; }
    
        public MyService(IUmbracoContextFactory context)
        {
            Context = context;
        }
    
        public IPublishedContent TypedContent(int id)
        {
            using (var cref = Context.EnsureUmbracoContext())
            {
                var cache = cref.UmbracoContext.Content;
                var node = cache.GetById(id);
                return node;
            }
        }
    
        public bool MemberHasAccess(string path)
        {
            // How?
        }
    }
    
  • Marc Goodson 2141 posts 14324 karma points MVP 8x c-trib
    Jan 07, 2020 @ 20:04
    Marc Goodson
    100

    Hi Bo

    The UmbracoHelper is made up of multiple bits and pieces - so when you are using it to query content, your actually using the implementation of IPublishedContentQuery... and with the MemberHasAccess method you are actually using the MembershipHelper class...

    So it may be as simple as injecting the MembershipHelper into your custom service...

    eg

    public class MyService : IMyService
    {
        public IUmbracoContextFactory Context { get; }
        private readonly MembershipHelper _membershipHelper ;
        public MyService(IUmbracoContextFactory context, MembershipHelper membershipHelper)
        {
            Context = context;
            _membershipHelper = membershipHelper;
        }
    
        public IPublishedContent TypedContent(int id)
        {
            using (var cref = Context.EnsureUmbracoContext())
            {
                var cache = cref.UmbracoContext.Content;
                var node = cache.GetById(id);
                return node;
            }
        }
    
        public bool MemberHasAccess(string path)
        {
            // this is I think how
    return _membershipHelper.MemberHasAccess(path);
        }
    }
    

    However this is a bit of a guess, as I'm not sure if the MembershipHelper relies on there being an UmbracoContext or not when it is injected, if it does this will all work fine if your custom service is only used in Controllers or Views where there is always an UmbracoContext but if you called it from a background thread, it may trigger a boot error...

    regards

    Marc

  • Bo Jacobsen 593 posts 2389 karma points
    Jan 08, 2020 @ 12:04
    Bo Jacobsen
    0

    It worked. Thanks alot.

Please Sign in or register to post replies

Write your reply to:

Draft