Accessing DbContext from custom Class .Net Core

.net-core asp.net-core c# entity-framework entity-framework-core

Question

I must use a handler class that is created in the configure function of one application to access my DbContext.Startup.cs class. How can I utilize the database context that has been registered with the dependency injection container in my handler class?Startup.ConfigureServices method.

Here's my code:

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);

    //..............

}

Handler Type:

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();   

   //......         

   }
}
1
1
7/27/2019 11:35:55 PM

Accepted Answer

ZZZ_tmp
1
7/31/2017 1:44:00 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow