Skip to content
This repository was archived by the owner on Oct 17, 2018. It is now read-only.
This repository was archived by the owner on Oct 17, 2018. It is now read-only.

Make Microsoft.AspNetCore.DataProtection.DataProtectionProvider class static #120

@javiercn

Description

@javiercn

https://github.com/aspnet/DataProtection/blob/dev/src/Microsoft.AspNetCore.DataProtection.Extensions/DataProtectionProvider.cs

https://docs.asp.net/en/latest/security/data-protection/configuration/non-di-scenarios.html

This class is meant to be used in Non-DI scenarios as an entry point for creating a IDataProtectionProvider instance that can be used acrross the app to protect and unprotect data. As such, making it static will avoid any confusion of mixing it with DI enabled scenarios. The advantages are:

  • Clearly separates DI scenarios from non DI scenarios. (You can't register a static class in a DI Container)
  • Makes the class cleaner (The current implementation creates a whole data protection stack inside the constructor, and wraps the default implementation without any perceived benefit.
  • Is arguably less discoverable, it's easier to 'dot' into a static class and see a method that you can use to construct an instance of the thing that you want, than having to use 'new' on the type.
  • By doing all the setup in a constructor, we are cornering ourselves in the future if we wan't to do more complicated things inside the setup, like for example, caching existing DataProtectionProviders.

As a reference, here is the implementation as a static class

using System;
using System.IO;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.AspNetCore.DataProtection
{
    public static class DataProtectionProvider
    {
        public static IDataProtectionProvider Create(DirectoryInfo keyDirectory)
        {
            return Create(keyDirectory, setupAction: null);
        }

        public static IDataProtectionProvider Create(
            DirectoryInfo keyDirectory,
            Action<DataProtectionConfiguration> setupAction)
        {
            if (keyDirectory == null)
            {
                throw new ArgumentNullException(nameof(keyDirectory));
            }

            var serviceCollection = new ServiceCollection();
            var builder = serviceCollection.AddDataProtection();
            builder.PersistKeysToFileSystem(keyDirectory);

            if(setupAction != null)
            {
                setupAction(builder);
            }

            return serviceCollection.BuildServiceProvider().GetRequiredService<IDataProtectionProvider>();
        }
    }
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions