简体   繁体   中英

How to call a service inside a static class?

I'm making an extension class to get user email, but I cannot refer to ApplicationDbContext service.

public static class Extensions
{
    // private static readonly ApplicationDbContext _dbContext;

    // static Extensions(ApplicationDbContext dbContext)
    // {
    //     _dbContext = dbContext;
    // }

    public static string GetUserEmail(this ClaimsPrincipal principal)
    {
        string email = string.Empty;

        string userid = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "";

        if (!string.IsNullOrEmpty(userid))
        {
            email = _dbContext.Users.Single(x => x.Id == userid).Email;
        }

        return email;
    }
}

Useage:

string email = User.GetUserEmail();

But static class cannot contain any parameter. Also, I don't want to pass dbContext as a parameter to GetUserEmail method.

Is there another way to do it?

Use the usermanager to get that information

// Inject UserManager<IdentityUser> into your controller or service
var user = await userManager.GetUserAsync(this.User); // pass ClaimsPrincipal
var email = await usermanager.GetEmailAsync(user);

Can you use a static initialization method?

public class Extensions
{
    private static ApplicationDbContext _dbContext { get; set; }

    public static void Init(ApplicationDbContext dbContext)
    {
        this._dbContext = dbContext;
    }
}

Usage

Extensions.Init(dbContext);
var email = User.GetEmail();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM