Search code examples
c#asp.netserenity-platform

Overriding how serenity framework handles [ConnectionKey] attribute


Serenity has the class attribute ConnectionKey which allows you to specify the key for which connection string you want to use.

Code Example below:

    [ConnectionKey("Default"), Module("Administration"), TableName("Languages")]
    [DisplayName("Languages"), InstanceName("Language")]
    [ReadPermission(PermissionKeys.Translation)]
    [ModifyPermission(PermissionKeys.Translation)]
    [LookupScript(typeof(Lookups.LanguageLookup))]
    public sealed class LanguageRow : Row, IIdRow, INameRow
    {
        [DisplayName("Id"), Identity]
        public Int32? Id
        {
            get { return Fields.Id[this]; }
            set { Fields.Id[this] = value; }
        }
    }

In my case I am making use of AWS Secret Manager to hide any sensitive information so the connection string itself isn't sitting in my appsettings but rather an AWS secret key. Therefore when this code gets hit it throws an error because the secret key isn't a valid connection string.

To get the actual connection string I first need to make a request to the AWS Secret Manager.

In their documentation about a third of the way down the page, in the SqlConnections.New method section, they mention how I can specify a connection string that doesn't exist in my appsettings. However, I don't see how I could apply this solution to my particular problem.

Is there a way to override how Serenity handles this ConnectionKey or any other workaround for this problem?


Solution

  • My final solution to the problem was to make use of the static method inside the SqlConnections class, SetConnection which allowed me to associate a different connection string with the default connectionKey.

    var csInfo = SqlConnections.GetConnectionString("SecretConnectionKey");
    
    var connectionString = SecretManagerService.GetSecretAsync(csInfo.ConnectionString, RegionEndpoint.USEast1).Result;
    
    SqlConnections.SetConnection("Default", connectionString, csInfo.ProviderName);
    

    This piece of code was placed at the bottom of the Configure method in startup.

    For this to work you would also need to add an empty default ConnectionString inside your appsettings.json files.

    {
      "Data": {
        "SecretConnectionKey": {
          "ConnectionString": "secretkey",
          "ProviderName": "System.Data.SqlClient"
        },
        "Default": {
          "ConnectionString": "",
          "ProviderName": "System.Data.SqlClient"
        }
      },
    

    I recognise that this is indeed a hacky approach but a time effective solution couldn't be found and this would be replaced with the upgrade to .Net 5.0.