【发布时间】:2017-07-31 01:37:08
【问题描述】:
我需要从一个处理程序类访问我的 DbContext,该处理程序类在 Startup.cs 类的配置方法中实例化。如何实例化我的处理程序类以使用在Startup.ConfigureServices 方法中使用依赖注入容器注册的数据库上下文。
这是我的代码:
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();
//......
}
}
【问题讨论】:
标签: c# entity-framework asp.net-core .net-core entity-framework-core