没有 Autofac 的 Azure 存储 Blob

Azure Storage Blob without Autofac

我们正在开发 .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 中实现相同的功能?

据我所知,Autofac用于DI。如果您不想使用它,您可以直接将内容上传到您的存储帐户,如下所示:

string connString = "the connection string from portal for your storage account, DefaultEndpointsProtocol=https;AccountName=storagetest789;AccountKey=G36m***==;EndpointSuffix=core.windows.net";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connString);
CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer =cloudBlobClient.GetContainerReference("container_name");
cloudBlobContainer.CreateIfNotExists();
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference("blob_name");
cloudBlockBlob.UploadFromFile("file_path");

建议:

为避免重新创建CloudBlobClient,您可以创建一个工厂class,它可以直接生产CloudBlobContainerCloudBlockBlob

并且,您可以使用 Microsoft official DI implementation。并在 Starup.

注册你的工厂
//For example, the interface is IStorageFactory, and your implementation is MyStroageFactory
services.AddSingleton<IStorageFactory, MyStroageFactory>();

然后,您可以注入工厂。例如,在控制器中:

public class HomeController : Controller
{

    private IStorageFactory _myStorageFactory;

    public HomeController(IStorageFactory myStorageFactory)
    {
        _myStorageFactory = myStorageFactory;
    }

    public IActionResult Index()
    {
        //For example, I defined a getCloudBlockBlob method in factory
        CloudBlockBlob cloudBlockBlob = _myStorageFactory.getCloudBlockBlob("container_name","blob_name");
        cloudBlockBlob.UploadFromFile(....);

        return Ok("Uploaded!");
    }

}