使用MVC和EF6代码优先方法,我能够集成Azure MSI令牌并执行CRUD操作,但是如何执行必须将令牌注入DBContext的迁移:
对于执行CRUD查询,我使用传统的ADO.NET样式查询,如下所示,它的工作原理是:
您需要在DI中进行设置:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
//code ignored for simplicity
services.AddDbContext<AzureProvider>();
services.AddTransient<IDBAuthTokenService, AzureSqlAuthTokenService>();
}
DbContext
public partial class AzureProvider: DbContext
{
public IConfiguration Configuration { get; }
public IDBAuthTokenService authTokenService { get; set; }
public AzureProvider(IConfiguration configuration, IDBAuthTokenService tokenService, DbContextOptions<AzureProvider> options)
: base(options)
{
Configuration = configuration;
authTokenService = tokenService;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = Configuration.GetConnectionString("defaultConnection");
connection.AccessToken = authTokenService.GetToken().Result;
optionsBuilder.UseSqlServer(connection);
}
}
public class AzureSqlAuthTokenService : IDBAuthTokenService
{
public async Task<string> GetToken()
{
AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
var token = await provider.GetAccessTokenAsync("https://database.windows.net/");
return token;
}
}