代码之家  ›  专栏  ›  技术社区  ›  johnny 5

配置存储被释放

  •  0
  • johnny 5  · 技术社区  · 7 年前

    //I've also tried without this line
    services.AddDbContext<ConfigurationDbContext>(options 
        => options.UseSqlServer(connectionString));
    
    var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
    services.AddIdentityServer()
       .AddDeveloperSigningCredential()
       .AddAspNetIdentity<ApplicationUser>()
       .AddOperationalStore(options =>
       {
           options.ConfigureDbContext = builder =>
               builder.UseSqlServer(connectionString,
                s => s.MigrationsAssembly(migrationsAssembly));
    
            // this enables automatic token cleanup. this is optional.
            options.EnableTokenCleanup = true;
            options.TokenCleanupInterval = 30;
       })
       .AddConfigurationStore(options =>
       {
          options.ConfigureDbContext = builder =>
             builder.UseSqlServer(connectionString,
              s => s.MigrationsAssembly(migrationsAssembly));
    
       });
    

    我试图从api生成一个令牌,将identityserver作为客户端使用。有时ConfigurationDbContext已经被释放,有时在第一行抛出,有时在最后一行抛出

    private async Task<string> CreatePaymentsTokenAsync()
    {
        // Get client for JWT
        var idpClient = await this._configurationDbContext.Clients.Include(x => x.AllowedScopes)
            .FirstOrDefaultAsync(c => c.ClientId == Config.APIServerClientId);
        // Get scopes to set in JWT
        var scopes = idpClient.AllowedScopes.Select(s => s.Scope).ToArray();
        // Use in-built Identity Server tools to issue JWT
        var token = await _identityServerTools.IssueClientJwtAsync(idpClient.ClientId, 
            idpClient.AccessTokenLifetime, scopes, new[] { "MyApi" });
        return token;
    }
    

    这段代码偶尔会工作,但大多数时候它会抛出一个错误,即上下文被处理了,你知道为什么吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   johnny 5    7 年前

    我建议不要使用底层的DbContext,而是使用IClientStore。

    _configurationDbContext 在IoC容器中确定范围?感觉它可能比DbContext有更长的生命周期,因此最终尝试访问已处置的实例。

    这也可能是因为你忘记了等待某个地方,这导致你的代码被触发并忘记

    await CreatePaymentsTokenAsync()
    
        2
  •  1
  •   sarvasana    7 年前

    等待的CreatePaymentsTokenAsync()在哪里?该方法是否声明为异步?

    推荐文章