Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ASP.Net 5 configuration and backwards compatibility with Class Libraries

Tags:

c#

asp.net

I've got multiple legacy libraries which configure themselves via the ConfigurationManager. Example:

var port = ConfigurationManager.AppSettings["service.port"];

The new ASP.Net system prefers strongly typed models based on an additional "config.json" file. Example (taken from Rick Strahl's Web Log):

//from AppSettings.cs
public class AppSettings
{
    public string SiteTitle { get; set; }
}

//from config.json
{
    "AppSettings": {
        "SiteTitle": "WebApplication2",
    },
    "Data": {
        "DefaultConnection": {
            "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=blahfoo;Trusted_Connection=True;MultipleActiveResultSets=true"
        }
    }
}

// from Startup.cs
public class Startup
{
    public IConfiguration Configuration { get; set; }

    public Startup(IHostingEnvironment env)
    {
        // Setup configuration sources.
        var configuration = new Configuration()
            .AddJsonFile("config.json")
            .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);

        configuration.AddEnvironmentVariables();
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        // Add Application settings to the services container.
        services.Configure<AppSettings>(Configuration.GetSubKey("AppSettings"));

        …
    }
}

My question: Is there a way to embrace the new ASP.Net 5 and it's strongly typed configuration methodology while maintaining backwards compatibility with my other application libraries?

Or rather, can I utilize common libraries from our portfolio without having to rewrite them?

like image 277
Will Bellman Avatar asked Feb 01 '26 07:02

Will Bellman


1 Answers

Your problem is that you relied on a concrete implementation of configuration and used the ConfigurationManager's static members from your classes instead of writing a SOLID implementation with proper dependency injection.

You could find some hacky tricks where you don't have to change your code to make use of the new configuration model, but I reckon you should do yourself a favour and use this as an opportunity to actually re-factor your code and abstract your current configurations behind one simple interface like e.g.:

public interface IMyAppConfiguration { string Setting1 { get; } string Setting2 { get; } SomeOtherMoreComplexSetting Setting3 { get; } }

Then inject this dependency in every class where you require one of the settings and provide one implementation which wraps the current ConfigurationManager class and another implementation which wraps the new configuration model.

This is a perfect example why SOLID design is important and makes code maintenance and innovation easier when done right.

like image 170
dustinmoris Avatar answered Feb 02 '26 23:02

dustinmoris