我目前正在尝试构建一个密封的类,该类通过存储在JSON中的设置来获取Azure存储的配置。我将设置注册在startup.cs类中,然后将其注入到构造函数中。问题是当我需要在该类中启动同一类时,因为它是密封的类
public sealed class AzureFileStorage
{
private static volatile AzureFileStorage instance;
private static object syncRoot = new Object();
private readonly AzureBlobSettings _azureBlobSettings;
public CloudStorageAccount StorageAccount { get; private set; }
public CloudBlobClient BlobClient { get; private set; }
public CloudBlobContainer Container { get; private set; }
public AzureFileStorage(IOptions<AzureBlobSettings> fbAuthSettingsAccessor)
{
_azureBlobSettings = fbAuthSettingsAccessor.Value;
StorageAccount = CloudStorageAccount.Parse(_azureBlobSettings.BlobStorageConnectionString);
//instantiate the client
BlobClient = StorageAccount.CreateCloudBlobClient();
//set the container
Container = BlobClient.GetContainerReference(_azureBlobSettings.ContainerBlobAzureId);
}
public static AzureFileStorage Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new AzureFileStorage(????);
}
}
return instance;
}
}
}
如果通过依赖项注入传递了azureblobsettings,我该如何初始化azurefilestorage。
答案 0 :(得分:0)
正如评论者所暗示的那样,当前设计不适用于依赖项注入。
应该重构AzureFileStorage
类,以删除单例实例,并使其具有自己的抽象。
public interface IAzureFileStorage {
CloudStorageAccount StorageAccount { get; }
CloudBlobClient BlobClient { get; }
CloudBlobContainer Container { get; }
}
public sealed class AzureFileStorage : IAzureFileStorage {
private readonly AzureBlobSettings _azureBlobSettings;
public AzureFileStorage(IOptions<AzureBlobSettings> fbAuthSettingsAccessor) {
_azureBlobSettings = fbAuthSettingsAccessor.Value;
StorageAccount = CloudStorageAccount.Parse(_azureBlobSettings.BlobStorageConnectionString);
//instantiate the client
BlobClient = StorageAccount.CreateCloudBlobClient();
//set the container
Container = BlobClient.GetContainerReference(_azureBlobSettings.ContainerBlobAzureId);
}
public CloudStorageAccount StorageAccount { get; private set; }
public CloudBlobClient BlobClient { get; private set; }
public CloudBlobContainer Container { get; private set; }
}
并在服务集合中注册为单身人士
public void ConfigureServices(IServiceCollection services) {
//...
service.AddSingleton<IAzureFileStorage, AzureFileStorage>();
//...
}
为了将IAzureFileStorage
显式地注入到任何地方,
private readonly IAzureFileStorage fileStore;
public SomeClass(IAzureFileStorage fileStore) {
this.fileStore = fileStore;
}
同一实例将在整个应用程序中使用。