Every time I spin up a fresh copy of test site for one of my products , I need some blocks of JSON in appsettings.json to make sure everything is configured correctly what I usually forget. There is an easy way to configure this automatically in .net.
Test Configuration for SEOChecker
Let's take SEOChecker for example. Every time I spin up a fresh copy of the SEOChecker test site, I need the same two blocks of JSON in appsettings.json so that it can send emails(using papercut) and all social options are enabled.
"Smtp": {
"From": "test@test.com",
"SecureSocketOptions": "None",
"Host": "127.0.0.1"
},
"SEOChecker": {
"SocialSettings": { "FaceBookEnabled": true, "TwitterEnabled": true }
}
Why appsettings.json configuration isn't the only way
It's easy to think of appsettings.json as the configuration for a .NET app, but it's really just one source feeding into IConfiguration. By default a host builds configuration from a stack of providers, layered in order, each one able to override the values below it — appsettings.json, then appsettings.{Environment}.json, then user secrets, then environment variables, then command-line arguments. Umbraco and ASP.NET Core both build on this, which is exactly why editing JSON has always felt like the only option available.
The other half of the picture is the options pattern, which is how that raw configuration turns into a strongly-typed object your code actually consumes:
builder.Services.Configure<SEOCheckerAppSettings>(
builder.Configuration.GetSection("SEOChecker"));
Update my ModifyStarterKitForSEOCheckerUse
As mentioned in an earlier post I love to have some automation to setup test environments. This method evolved over the years and I added a ModifyStarterkit project to all products that brings the site (with starterkit) to an initial state, install content, run migrations, that kind of thing via a composer. The last thing I had to do was to configure the SMTP settings and SEOCheckerAppSettings using builder.Service.Configure in code and never have to worry about forgetting configuration again
[ComposeAfter(typeof(SEOCheckerComposer))]
public class ModifystarterKitComposer : IComposer
{
public void Compose(IUmbracoBuilder builder)
{
builder.Services.AddTransient<IModificationHelper, ModificationHelper>();
builder.AddNotificationHandler<UmbracoApplicationStartingNotification, ModificationInstaller>();
builder.Services.Configure<GlobalSettings>(options =>
{
options.Smtp = new SmtpSettings
{
From = "test@test.com",
Host = "127.0.0.1",
SecureSocketOptions = SecureSocketOptions.None,
};
});
builder.Services.Configure<SEOCheckerAppSettings>(options =>
{
options.SocialSettings.FaceBookEnabled = true;
options.SocialSettings.TwitterEnabled = true;
});
}
}
That's it
And that was all needed to make sure the whole test site was configured correctly and I can immediately use it instead of doing some manual configuration first .