[英]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. 我正在扩展类以获取用户电子邮件,但是我无法引用
ApplicationDbContext
服务。
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. 另外,我不想将
dbContext
作为参数传递给GetUserEmail
方法。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.