1
我需要從一個處理類中訪問我的DbContext,該類在Startup.cs
類的configure方法中實例化。如何實例化我的處理程序類以便使用在Startup.ConfigureServices
方法中使用依賴注入容器註冊的數據庫上下文。從自定義類.Net核心訪問DbContext
這是我的代碼:
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
var connection = @"Server=MyDb;Initial Catalog=MYDB;Persist Security Info=True; Integrated Security=SSPI;";
services.AddDbContext<iProfiler_ControlsContext>(options => options.UseSqlServer(connection));
//.........
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//.............
options.SecurityTokenValidators.Add(new MyTokenHandler(MY INSTANCE OF DBCONTEXT HERE));
app.UseJwtBearerAuthentication(options);
//..............
}
處理類:
internal class MyTokenHandler : ISecurityTokenValidator
{
private JwtSecurityTokenHandler _tokenHandler;
private iProfiler_ControlsContext _context;
public MyTokenHandler(iProfiler_ControlsContext context)
{
_tokenHandler = new JwtSecurityTokenHandler();
_context = context;
}
public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
{
var principal = _tokenHandler.ValidateToken(securityToken, validationParameters, out validatedToken);
var tblVerificationPortalTimeStamps = _context.TblVerificationPortalTimeStamps.ToList();
//......
}
}