【问题标题】:Accessing DbContext from custom Class .Net Core从自定义类 .Net Core 访问 DbContext
【发布时间】: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


    【解决方案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);
    
       //..............
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-15
      • 1970-01-01
      • 2023-01-28
      • 1970-01-01
      • 2019-03-10
      • 2011-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多