umbraco / Umbraco.StorageProviders

MIT License
29 stars 21 forks source link

Add CreateIfNotExists helper method for Azure Blob Storage #29

Closed ronaldbarendse closed 2 years ago

ronaldbarendse commented 2 years ago

This closes https://github.com/umbraco/Umbraco.StorageProviders/issues/6 by allowing you to (more easily) create the container if it doesn't exist yet (you need to explicitly opt-in, because it requires create/write permissions, does a service request and you need to specify the access type, see Azure Storage Blobs-azure-storage-blobs-models-blobcontainerencryptionscopeoptions-system-threading-cancellationtoken))/legacy docs).

I've not added this as an extra option to AzureBlobFileSystemOptions, because the creation should be done only once during runtime (so not during configuration) and also not within the AzureBlobFileSystem constructor. It's still best practice to ensure the configured container is already created, but this might make development/testing a bit easier.

The following code should automatically create the container on application startup:

using Microsoft.Extensions.Options;
using Umbraco.Cms.Core.Composing;
using Umbraco.StorageProviders.AzureBlob.IO;

public class AzureBlobFileSystemComposer : ComponentComposer<AzureBlobFileSystemComponent>
{ }

public class AzureBlobFileSystemComponent : IComponent
{
    private readonly IOptionsMonitor<AzureBlobFileSystemOptions> _options;

    public AzureBlobFileSystemComponent(IOptionsMonitor<AzureBlobFileSystemOptions> options) => _options = options;

    public void Initialize()
    {
        var options = _options.Get(AzureBlobFileSystemOptions.MediaFileSystemName);
        AzureBlobFileSystem.CreateIfNotExists(options);
    }

    public void Terminate()
    { }
}
ronaldbarendse commented 2 years ago

Note that when creating the container in the Action<AzureBlobFileSystemOptions> configure callback, this will also be executed during runtime, but for each time an IOptions<AzureBlobFileSystemOptions> is requested from the DI container (which might result in calling this multiple times during the lifetime of the application).

So use the following with caution:

.AddAzureBlobMediaFileSystem(options => {
  options.ConnectionString = "";
  options.ContainerName = "";

  AzureBlobFileSystem.CreateIfNotExists(options);
})