How do I inject ASP.NET 5 (vNext) user-secrets into my own utility class?

A class for your settings:

public class AwsSettings
{
    public string AccessKey { get; set; } = string.Empty;
    public string AccessSecret{ get; set; } = string.Empty;
}

if your settings were in config.json you would do it like this:

{
  "AwsSettings": {
    "AccessKey": "yourkey",
    "AccessSecret": "yoursecret"
  }
}

in Startup you would need this:

services.Configure<AwsSettings>(Configuration.GetSection("AwsSettings"));

your mailer class would need the settings injected into constructor

using Microsoft.Framework.OptionsModel;

public class MailHelper
{
    public MailHelper(IOptions<AwsSettings> awsOptionsAccessor)
    {
        awsSettings = awsOptionsAccessor.Options;
    }
    private AwsSettings awsSettings;

    ... your other methods

}

UserSecrets is just another configuation source so instead of config.json you can put the settings there but you need to simulate the structure so it can map to your class so you set them like this with colons:

user-secret set "AwsSettings:AccessKey" "my access key" and
user-secret set "AwsSettings:AccessSecret" "my secret key"

that is equivalent to the structure I showed for config.json

now the settings will be loaded from user secrets and injected into your mailer

Leave a Comment