Best practice for handling appsettings values

2.8k views Asked by At

I'm trying to write code as better I can, for that reason looking at some code I wrote in past I've seen that I access to .config appsetting with something as

 Public void Do()
{
 Var x = ConfigurationManager.AppSettings.Get("foo");
 doSomethingElse(x);
}

Writing test on this method I asked myself wasn't it better to have an interface with properties that exposes all the .config AppSettings values ? This would allow me to replace via IoC the real implementation.

on the other side I ask is it correct to wrap all those values in a class/interface?what if I've different assemblies that compose an application and I need to access to that object? Supposed that it will be in a shared project does it make sense to have a value as

 Int ModelAvalue {get{};}

Defined in that class that would never be used in ModelB?

1

There are 1 answers

3
Matthew On BEST ANSWER

Configuration is a dependency. I think your idea about creating an interface that returns the most appropriate type helps both with testing and makes your code easier to understand. It also gives you the flexibility to change where your configuration is stored in the future.

To answer your other question, it would be better to have interfaces smaller and more specific, as per the interface segregation principle. You could have different interfaces in which each interface is a group of closely related settings. For example, you would not have an interface that has your database connection string and your log file path.

public interface IDatabaseConfiguration
{
    string ConnectionString { get; }
}

public interface IBlogConfiguration
{
    int NumberOfPostsPerPage { get; }
}

public class AppConfiguration : IDatabaseConfiguration, IBlogConfiguration
{
    public string ConnectionString 
    {
        get { return ConfigurationManager.ConnectionStrings["MyDb"].ConnectionString; }
    }

    public int NumberOfPostsPerPage 
    {
        get { return int.Parse(ConfigurationManager.AppSettings["PostsPerPage"]); }
    }
}

In the future, if you decide that NumberOfPostsPerPage should be stored elsewhere, you can create a different concrete implementation of IBlogConfiguration