如何通过选项配置在自定义私有DbContext包中设置Azure默认TenantId

问题描述 投票:0回答:1

我正在使用我公司的自定义 DbContext 作为私有包。 包实现如下所示:

namespace Company.Data.CompanyServices

    {
        public class CompanyServicesDbContext : DbContext
        {
            public virtual DbSet<Account> Accounts { get; set; }
    
            public virtual DbSet<Administration> Administrations { get; set; }
    
            public virtual DbSet<MfaStatus> MfaStatuses { get; set; }
             .....
             public CompanyServicesDbContext (DbContextOptions options)
                : base(options)
            {
            }
            .......
        }
    }

我想设置默认的Azure

tenantId
获取token并操作db

问题是我有不同的 Azure 租户,如果我没有登录到正确的租户,当我使用我的 Visual Studio 在本地运行它时,我的应用程序会失败。

我知道这是因为我的应用程序从其他租户那里获取了错误的令牌,我登录了。

如果我正在创建我的应用程序 dbContext,我可以通过以下实现来实现:

     public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
            {
                var tokenRequestContext = new TokenRequestContext(new[] { "https://database.windows.net/" }, null, null,
                tenantId = "xxxx-xxxx-xxxx-xxxx" //👈 passing the default tenantId here
                );
                var accessToken = (new DefaultAzureCredential()).GetToken(tokenRequestContext);
                var conn = (Microsoft.Data.SqlClient.SqlConnection)this.Database.GetDbConnection();
                conn.AccessToken = accessToken.Token;
    
            }

但是我用的是私有的DbContext包,不能改包码

当我使用私有包并使用它的实现时,有没有办法通过配置选项传递令牌?

c# asp.net azure visual-studio entity-framework-core
1个回答
1
投票

由于这是一个内部包,包维护者应该为您提供:

  • 使用简洁的助手自行注册扩展的选项 方法并允许从您那里传递 tenantId
  • 允许/公开某种 appSetting 部分供您添加到您的配置中,这样您只添加一个配置值,然后包应该在内部查找该部分(很像它可能会获取连接字符串)以便您不知道它是如何使用的,但你需要记住将配置添加到你的应用程序配置文件
© www.soinside.com 2019 - 2023. All rights reserved.