Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to web.config files in ASP.NET

In my experience, web.config files are widely reviled. In particular, I have found them difficult to manage when you have multiple environments to support, and fiddly to update due to the lack of validation at update-time and the verbosity of XML.

What are the alternatives?

like image 844
Ben Aston Avatar asked Jan 22 '23 23:01

Ben Aston


1 Answers

I personally don't mind Web.Config for small one-off applications, but for anything substantial I avoid using them for application configuration.

Here's what I do...

  • I define one or more interfaces for my configuration depending on the complexity.
  • I create different implementations per environment (dev, stage, prod, etc.)
  • I use an abstract base class to define common configuration.
  • I then use Ninject for dependency injection so the appropriate implementation is provided depending on which environment I am targeting.
  • I always code to the configuration interfaces and benefit from compile time checks.

Here's an example...

// Config Contract
public interface IWebAppConfig
{
     string SmtpHost { get; }
     string RootUrl { get; }
}

// Define Common Config Values (values that don't change per environment) 
public abstract class AbstractWebAppConfig : IWebAppConfig
{
     public string SmtpHost { get { return "smtp.google.com"; } }
     public abstract RootUrl { get; }
}

// Dev Config Settings
public class DevWebAppConfig : AbstractWebAppConfig
{
     public override string RootUrl { get { return "http://localhost:1322"; } }
}

// Stage Config Settings
public class StageWebAppConfig : AbstractWebAppConfig
{
     public override string RootUrl { get { return "http://stage.mysite.com"; } }
}

// Prod Config Settings
public class ProdWebAppConfig : AbstractWebAppConfig
{
     public override string RootUrl { get { return "http://www.mysite.com"; } }
}

Advantages of this approach:

  • Type Safe
  • Configuration is represented as objects not key value pairs (useful for passing logical groupings of config values instead of multiple values)
  • Easier to Unit Test classes that are dependent on configuration values
  • Sharing configuration across multiple apps is trivial
  • Deploying the assembly that contains the configuration implementations will trigger a recycle of the application pool, much like re-deploying a web.config.

You may still use the web.config to define the environment, which is what I usually do by adding the following to the appSettings:

<appSettings>
     <!-- accepts: dev|stage|prod -->
     <add key="Env" value="dev" />
</appSettings>

Alternatively, it could be machine based by using Envrionment Variables, or some other construct.

like image 66
ctorx Avatar answered Jan 25 '23 13:01

ctorx