Copied to clipboard

Flag this post as spam?

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


  • Tom Bruce 122 posts 506 karma points
    Mar 15, 2021 @ 11:58
    Tom Bruce
    0

    Umbraco 8 - ApplicationContext

    Hi everyone, from Umbraco documentation it’s clear that we shouldn’t use n Singleton accessors like: ApplicationContext.Current or UmbracoContext.Current.

    But I’m not sure how to re-write this piece of code to the new guidelines any help or pointers much appreciated.

    var tempMember = ApplicationContext.Current.Services.MemberService.GetByEmail(email);
    
  • Kevin Jump 2342 posts 14889 karma points MVP 8x c-trib
    Mar 15, 2021 @ 12:43
    Kevin Jump
    101

    Hi Tom,

    it depends a little bit on where that line of code is running from:

    if you are ruining it in a Controller. that inherits something like UmbracoAuthorizedController, UmbracoApoController or SurfaceController you can access the services via the Services member/

    Services.MemberService.GetByEmail(email). 
    

    if its in your own code class, then you should use Dependency Injection to include the MemberService in the class.

    public class MyMemberThing
    {
        private readonly IMemberService _memberService;
    
        public MyMemberThing(IMemberService memberService)
        {
            _memberService = memberService;
        }
    
        public void MyEmailMethod(string email)
        {
            _memberService.GetByEmail(email);
        }
    }
    

    if you do this, you need to register your class via a 'composer' . this runs at startup and does the dependency injection magic for you. so what ever needs your membersthing class can use it in the same way and it will get the MemberService sent to its constructor.

    public class MyMemberComposer : IUserComposer
    {
        public void Compose(Composition composition)
        {
            composition.Register<MyMemberThing>();
        }
    }
    

    if you are doing this is razor. (as cshtml) file then you will probibly have to use Current.

    @using Umbraco.Web.Composing;
    Current.Services.MemberService.GetByEmail(email)
    

    If you are in razor you are probably better using the Membership Helper. e.g

      var username = Membership.GetUserNameByEmail(email);
    
  • Tom Bruce 122 posts 506 karma points
    Mar 15, 2021 @ 12:45
    Tom Bruce
    0

    Thanks Kevin :)

Please Sign in or register to post replies

Write your reply to:

Draft