假设我具有以下结构化的项目层,例如存储库->服务-> 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中,我将JWT令牌与“ OnTokenValidated”事件一起使用,以从令牌中获取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信息!

最佳答案

您可以通过在启动中将IUserInfo注册为服务来注入它。

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

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

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

10-09 03:31