Devo accedere al mio DbContext da una classe handler che viene istanziata nel metodo configure della classe Startup.cs
. Come può istanziare la classe del gestore per utilizzare il contesto db registrato nel contenitore di iniezione delle dipendenze nel metodo Startup.ConfigureServices
.
Questo è il mio codice:
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);
//..............
}
Classe del gestore:
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();
//......
}
}
Primo aggiornamento ConfigureServices
per restituire un fornitore di servizi dalla raccolta di servizi.
public IServiceProvider 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));
//.........
var provider = services.BuildServiceProvider();
return provider;
}
Prossimo aggiornamento Configure
metodo per iniettare IServiceProvider
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory, IServiceProvider provider) {
//.............
var dbContext = provider.GetService<iProfiler_ControlsContext>();
options.SecurityTokenValidators.Add(new MyTokenHandler(dbContext));
app.UseJwtBearerAuthentication(options);
//..............
}