Accessing DbContext from custom Class .Net Core

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

Question

I need to access my DbContext from one handler class which is instantiated in the configure method of Startup.cs class. How Can Instantiate my handler class in order to use the db context registered with the dependency injection container in Startup.ConfigureServices method.

This is 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 Class:

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

First update ConfigureServices to return a service provider from the service collection.

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

Next update Configure method to inject 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);

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

}
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