據我所知,您可以利用您的代碼來初始化您的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");
}
}