2016-11-11 81 views
0

在我的ASP.NET Core應用程序中,我使用了很多Azure服務,例如表存儲,DocumentDb等。作爲初始化例程的一部分,我需要確保這些數據庫存在,如果不存在,我需要創建它們。在ASP.NET Core應用程序中初始化數據庫

目前,我使用下面的代碼在Startup.cs的Configure方法中處理初始化。

// Initialize databases 
using (var serviceScope = app.ApplicationServices 
      .GetRequiredService<IServiceScopeFactory>() 
      .CreateScope()) 
      { 
      var blobClient = serviceScope.ServiceProvider.GetService<MyBlobStorageClient>(); 
      var dbClient = serviceScope.ServiceProvider.GetService<MyDocumentDbClient>(); 
      var tsClient = serviceScope.ServiceProvider.GetService<MyTableStorage.TableStorageClient>(); 
      MyInitializer(blobClient, dbClient, tsClient).Wait(); 
      } 

這是我應該如何處理我的初始化?

回答

1

據我所知,您可以利用您的代碼來初始化您的Azure服務。另外,您可以添加StorageClient/DocumentDbClient的單例服務,並檢查您的服務是否存在,並在對Azure服務執行CURD操作之前創建特定資源(如果不存在)。這裏是我的AzureBlobStorageClient的代碼片段,你可以參考它。

Startup.cs

public void ConfigureServices(IServiceCollection services) 
{ 
    services.AddOptions(); 
    services.Configure<AzureStorageConfig>(Configuration.GetSection("AzureStorageConfig")); 
    services.AddSingleton<AzureBlobStorageClient>(); 
    services.AddMvc(); 
} 

appsettings.json

"AzureStorageConfig": { 
    "AccountName": "<your-storage-account-name>", 
    "AccountKey": "<your-storage-account-key>" 
} 

AzureBlobStorageClient.cs

public class AzureBlobStorageClient 
{ 
    private CloudBlobClient _cloudBlobClient; 
    public AzureBlobStorageClient(IOptions<AzureStorageConfig> config) 
    { 
     var storageAccount = new CloudStorageAccount(new StorageCredentials(config.Value.AccountName, config.Value.AccountKey), true); 
     _cloudBlobClient=storageAccount.CreateCloudBlobClient(); 
    } 

    public async Task<bool> EnsureContainer(string containerName) 
    { 
     var storageContainer = _cloudBlobClient.GetContainerReference(containerName); 
     return await storageContainer.CreateIfNotExistsAsync(); 
    } 
} 

public class AzureStorageConfig 
{ 
    public string AccountName { get; set; } 
    public string AccountKey { get; set; } 
} 

AzureStorageController.cs

[Route("api/[controller]")] 
[Authorize] 
public class AzureStorageController : Controller 
{ 
    private AzureBlobStorageClient _storageClient; 
    public ValuesController(AzureBlobStorageClient storageClient) 
    { 
     _storageClient = storageClient; 
    } 

    [HttpGet] 
    public async Task<string> Get() 
    { 
     //_storageClient.EnsureContainer("<blob-container-name>"); 
     return await Task.FromResult("hello world"); 
    } 
} 
相關問題