从自定义类.Net Core访问DbContext

时间:2017-07-31 01:37:08

标签: c# entity-framework asp.net-core entity-framework-core

我需要从一个处理程序类访问我的DbContext,该处理程序类在Startup.cs类的configure方法中实例化。如何实例化我的处理程序类,以便在Startup.ConfigureServices方法中使用向依赖注入容器注册的db上下文。

这是我的代码:

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

   //......         

   }
}

1 个答案:

答案 0 :(得分:1)

首先更新ConfigureServices以从服务集合返回服务提供商。

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

下一次更新Configure方法以注入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);

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

}