2017-07-31 2 views
1

Startup.csクラスのconfigureメソッドでインスタンス化されているハンドラクラスからDbContextにアクセスする必要があります。 Startup.ConfigureServicesメソッドで依存関係注入コンテナに登録されたdbコンテキストを使用するために、ハンドラクラスをインスタンス化する方法サービスのコレクションからサービスプロバイダを返すためにカスタムクラス.Net CoreからDbContextにアクセス

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

    //......   

    } 
} 

答えて

0

まず更新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); 

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

} 

ハンドラ・クラス

は、これは私のコードです。 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); 

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

} 
を注入する

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方法

関連する問題