【发布时间】:2023-03-24 05:56:01
【问题描述】:
假设我从下到上有以下结构化项目层,如 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 令牌从令牌中获取 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 对象,但是当我在我的控制器中调试时,IUserInfo 总是代表一个空对象,就像在构造函数或 api 中一样方法。我知道我可能在 .Net 核心中滥用了依赖注入,所以请随时指导我将 IUserInfo 注入我的 Controller --> Service --> Repository 的正确方法,所以都可以得到实际的UserInfo信息!
【问题讨论】:
-
难道不需要注册 UserInfo 来进行 Scoped 操作吗?我可能错过了它,但我没有看到任何类似的东西。
-
建议审查当前的设计选择。配置后构建的服务不会受到在请求期间尝试添加其他服务的影响。
-
@DavidL:对不起,我忘记粘贴了,注册就像 services.AddScoped
();在 ConfigureServices 方法中。
标签: c# asp.net-core dependency-injection repository-pattern asp.net-core-webapi