我有一个类,该类具有执行Azure存储功能的方法,目前,每次调用StorageContainer,BlobClient和Container时,我都会创建它:
private readonly IAzureStorageConfig _config;
public SaveImageBlob(IAzureStorageConfig config)
{
_config = config;
}
public async Task<T> ExecuteAsync(ImageSaveInput input)
{
//get the storage account from the connection string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_config.ConnectionString);
//instantiate the client
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
//set the container
CloudBlobContainer container = blobClient.GetContainerReference(_config.ImagesContainerName);
//... do things and stuff
}
现在,我想将其从SaveImageBlob.ExecuteAsync方法中剔除,并将依赖项注入到类中,因此Azure存储项仅实例化一次。
我目前有这样的界面:
namespace Domain.Interfaces
{
public interface IAzureStorage
{
CloudStorageAccount StorageAccount { get; }
CloudBlobClient BlobClient { get; }
CloudBlobContainer Container { get; }
}
}
现在,我对如何实现该接口一无所知。
一旦实现了接口,我想我将把SaveImageBlob.ExecuteAsync方法更改为此:
private readonly IAzureStorageConfig _config;
private readonly IAzureStorage _storage;
public SaveImageBlob(IAzureStorageConfig config,
IAzureStorage storage)
{
_config = config;
_storage = storage;
}
public async Task<T> ExecuteAsync(ImageSaveInput input)
{
//now, since I don't have to create an instance of the storageAccount, blobClient, and container, I can just access them from _storage
//create the blockBlob
CloudBlockBlob blockBlob = _storage.Container.GetBlockBlobReference(input.BlobUrl);
//... do things and stuff with a Stream (doesn't really matter)
//upload the blob
blockBlob.UploadFromStreamAsync(stream);
//do more things and stuff and return something
}
我只需要知道如何实现该接口,就可以将AzureStorage类作为Singleton输入到SaveImageBlob。没关系,但是为了后代,我将Autofac用于DI。
最佳答案
单例的基本思想包括一个私有静态实例变量和一个公共静态Instance属性,该属性会线程安全地检查是否设置了实例变量,如果没有设置,则将其设置,然后返回它。
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
public sealed class AzureStorage
{
private static volatile AzureStorage instance;
private static object syncRoot = new Object();
public CloudStorageAccount StorageAccount { get; private set; }
public CloudBlobClient BlobClient { get; private set; }
public CloudBlobContainer Container { get; private set; }
private AzureStorage()
{
StorageAccount = CloudStorageAccount.Parse(_config.ConnectionString);
//instantiate the client
BlobClient = StorageAccount.CreateCloudBlobClient();
//set the container
Container = BlobClient.GetContainerReference(_config.ImagesContainerName);
}
public static AzureStorage Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new AzureStorage();
}
}
return instance;
}
}
}
留给读者的练习是提供配置。