gpt4 book ai didi

c# - .Net Core - 将 API 中间件中的依赖项 IUserInfo 注入(inject)到存储库层

转载 作者:行者123 更新时间:2023-11-30 13:43:45 25 4
gpt4 key购买 nike

假设我有以下结构化项目层,如 Repository -> Service -> API 从下到上,代码示例:

存储库:

public interface IUserInfo
{
int UID{ get; set; }
}
public class UserInfo : IUserInfo
{
public int UID { get; set; }
}
public class ProductionRepository : Repository, IProductionRepository {
public ProductionRepository(IUserInfo userInfo, StoreDbContext dbContext) : base(userInfo, dbContext)
{}
//...
}

服务:

public class ProductionService : Service, IProductionService {
public ProductionService(IUserInfo userInfo, StoreDbContext dbContext)
: base(userInfo, dbContext)
{
}
//...
}
public abstract class Service {
protected IProductionRepository m_productionRepository;
public Service(IUserInfo userInfo, StoreDbContext dbContext)
{
UserInfo = userInfo;
DbContext = dbContext;
}
protected IProductionRepository ProductionRepository
=> m_productionRepository ?? (m_productionRepository = new ProductionRepository(UserInfo, DbContext));
}

API:

  public class ProductionController : Controller {
private readonly IUserInfo userInfo;
protected IProductionService ProductionBusinessObject;
public ProductionController(IUserInfo _userInfo, IProductionService productionBusinessObject)
{
userInfo = _userInfo;
ProductionBusinessObject = productionBusinessObject;
}
}

现在,在我的 Startup.cs 中,我使用带有“OnTokenValidated”事件的 JWT token 从 token 中获取 UserInfo 信息:

services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Events = new JwtBearerEvents
{
#region Jwt After Validation Authenticated
OnTokenValidated = async context =>
{
#region Get user's immutable object id from claims that came from ClaimsPrincipal
var userID = context.Principal.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier)
services.Configure<UserInfo>(options =>
{
options.UID = userID;
});
#endregion
},
#endregion
}
};

我正在使用 services.Configure 并尝试将 UID 分配给 IUserInfo 对象,但是当我在我的 Controller 中进行调试时,IUserInfo 总是代表一个空对象,就像在构造函数或 api 中一样方法。我知道我可能滥用了 .Net 核心中的依赖注入(inject),所以请随时指导我将 IUserInfo 注入(inject)我的 Controller --> Service --> Repository 的正确方法,所以都可以获得真实的UserInfo信息!

最佳答案

您可以通过在 Startup 中将其注册为服务来注入(inject) IUserInfo

services.AddScoped<IUserInfo>(provider =>
{
var context = provider.GetService<IHttpContextAccessor>();

return new UserInfo
{
UID = context.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier)
};
});

关于c# - .Net Core - 将 API 中间件中的依赖项 IUserInfo 注入(inject)到存储库层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51143812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com