In my WebApiConfig.cs class for a .NET 4.6.1 WebApi project, I want to enable CORS only if an app setting in web.config is set to true. I generally read web.config AppSettings using an AppSettings class that converts the values from string to a more appropriate data type. I declare an IAppSettings interface and register the type with the Autofac DI container I'm using.
However, in this case, WebApiConfig is a static class, and its Register method is called as follows: GlobalConfiguration.Configure(WebApiConfig.Register); I can't change the signature of the GlobalConfiguration.Configure class, so I don't see how to inject the IAppSettings object to make it accessible in the Register method. Of course I can access ConfigurationManager, but that seems very hacky. Of course I could also declare AppSettings as a static class, but that would make unit testing difficult. Is there some cleaner way to do this?
Here's the relevant code - the ConfigurationManager line is the one I want to replace with a call to an appSettings class:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
if (System.Configuration.ConfigurationManager.AppSettings.Get("IsCorsEnabled", false))
{
config.EnableCors();
}
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Many thanks for any assistance!!