【发布时间】:2020-02-26 12:45:05
【问题描述】:
我们正在开发 .NET Core 3.0 Web-API 以将图像上传到 Azure blob 存储。我遇到了一个样本来达到同样的效果。
下面是 Startup.cs 中使用 Autofac 的部分,特别是 ContainerBuilder 和 IComponentContext。
private static void ConfigureStorageAccount(ContainerBuilder builder)
{
AzureTableStorageDebugConnectionString = Configuration["Azure:Storage:ConnectionString"];
builder.Register(c => CreateStorageAccount(AzureTableStorageDebugConnectionString));
}
private static CloudStorageAccount CreateStorageAccount(string connection)
{
if (String.IsNullOrEmpty(connection))
{
throw new Exception("Azure Storage connection string is null!");
}
return CloudStorageAccount.Parse(connection);
}
private static void ConfigureServicesWithRepositories(ContainerBuilder builder)
{
builder.RegisterType<ImageUploadService>().AsImplementedInterfaces().InstancePerLifetimeScope();
}
private static void ConfigureAzureCloudBlobContainers(ContainerBuilder builder)
{
builder.Register(c => c.Resolve<CloudStorageAccount>().CreateCloudBlobClient());
builder.Register(c => GetBlobContainer(c, UploadedImagesCloudBlobContainerName))
.Named<CloudBlobContainer>(UploadedImagesCloudBlobContainerName);
}
private static CloudBlobContainer GetBlobContainer(IComponentContext context, string blobContainerName)
{
var blob = context.Resolve<CloudBlobClient>().GetContainerReference(blobContainerName);
var createdSuccessfully = blob.CreateIfNotExistsAsync().Result;
if (createdSuccessfully)
{
blob.SetPermissionsAsync(new BlobContainerPermissions
{
PublicAccess = BlobContainerPublicAccessType.Blob
});
}
return blob;
}
private static void ConfigureCloudBlobContainersForServices(ContainerBuilder builder)
{
builder.RegisterType<ImageUploadService>()
.WithParameter(
(pi, c) => pi.ParameterType == (typeof(CloudBlobContainer)),
(pi, c) => c.ResolveNamed<CloudBlobContainer>(UploadedImagesCloudBlobContainerName))
.AsImplementedInterfaces();
}
是否可以完全摆脱 Autofac 并使用 Core 3.0 在 Startup.cs 中实现相同的功能?
【问题讨论】:
-
你能说得更具体点吗?你的目标是什么?我不认为你提供的实现是好的......
-
Startup不应将文件上传到 blob。您的服务应该根据请求执行此操作 -
@MartinBrandl 目标是在不使用 Autofac 的情况下将图像上传到 Azure Blob 存储。
-
@HariHaran 在上面的Startup.cs代码中,没有上传。上传实现已投入使用。
-
@HariHaran 是的,它是从博客中复制的,但并非毫无意义。我还想在 .NET Core 3.0 Web-API 中实现存储库模式。 Autofac 充当控制反转容器。
标签: c# azure azure-blob-storage autofac asp.net-core-webapi