2

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 Answer 1

1

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

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

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.