c# - 哪里是处理在 AddDbContext 中创建的 SqlConnection 对象的好地方? (.Net 核心 2.2)

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

我正在尝试让 Azure 的托管身份验证与我将部署在 Azure 应用服务上以连接到 Azure SQL Server 的应用程序一起使用。

在查看了一些示例和示例代码后,我正在尝试以下实现:

services.AddDbContext<MainContext>(optionsBuilder =>
{
    SqlConnection connection = new SqlConnection();
    connection.ConnectionString = Configuration.GetConnectionString("DefaultConnection");
    connection.AccessToken = (new AzureServiceTokenProvider()).GetAccessTokenAsync("https://database.windows.net/").Result;

    optionsBuilder.UseSqlServer(connection);
});

哪里是处理此 SqlConnection 的正确位置?有没有更好的方法来实现这个 AccessToken 设置?

最佳答案

您可以尝试先正常注册您的上下文:

services.AddDbContext<MainContext>(builder => 
               builder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

根据documentation ,这默认注册为“Scoped”,因此连接将在每次​​请求时自动打开和关闭。

The AddDbContext extension method registers DbContext types with a scoped lifetime by default.

然后,检索注册的上下文并添加访问 token ,如下所示:

services.AddScoped<MainContext>(serviceProvider => {
      var dbContext = serviceProvider.GetRequiredService<MainContext>();  
      var connection = dbContext.Database.GetDbConnection() as SqlConnection;
      if(connection == null) {
          return dbContext;
      }
      connection.AccessToken = (new AzureServiceTokenProvider()).GetAccessTokenAsync("https://database.windows.net/").Result;
      return dbContext;
});

现在,对于每个请求,都会为您创建和处理连接,并且会检索访问 token 。

另一种方式(可能更简洁)是从您的上下文继承并在构造函数中添加 token :

public class ContextWithAccessToken : MainDbContext 
{
    public ContextWithAccessToken(DbContextOptions options) : base(options)
    {
        var connection = (SqlConnection)this.Database.GetDbConnection();
        connection.AccessToken = (new AzureServiceTokenProvider()).GetAccessTokenAsync("https://database.windows.net/").Result;
    }
}

然后只需注册此上下文即可:

services.AddDbContext<ContextWithAccessToken>(builder => 
               builder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

关于c# - 哪里是处理在 AddDbContext 中创建的 SqlConnection 对象的好地方? (.Net 核心 2.2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56578019/

相关文章:

c# - 实体类型需要定义主键,且 key 属性错误

sql-server - Entity Framework 7 无法插入日期时间

c# - 使用 FreeImage 对 JPEG 进行无损优化

c# - 从 C# 到 SQL Server 的精度损失

c# - 如何在 ASP.NET Core 中定义和使用不同的用户类型

c# - ASP.NET Core Razor Pages v6 中@page 的静态定义路由

c# - 实体类型的实例...无法跟踪,因为已跟踪具有相同键的该类型的另一个实例

c# - 如何在 Windows 服务中连续读取文本文件

c# - 将页面控制从 jscript 传递到代码隐藏中的 pagemethod?

asp.net - Docker错误: dotnet-file. dll不存在