I am working on a typical .net web app which is first deployed at test environment - ENV- T and then after complete testing it is moved to Production ENV - P. Our hosting provider will not deploy anything directly on Prod instead it is first deployed on Test and then they sync it to PROD.
Also these two environment Env-T and Env-P are totally different. So the Web.Config settings are different too.
So to deploy anything on ENV-P we have to change the web.config of ENV-T as per Env-P. And then ask the hosting vendor to sync the application and then we have to revert.
To solve this issue i thought of making the Web.config environment independent. So i wrote a custom ConfiguraitonManager class which will identify the current environment in which the application is working in and will load values accordingly.
High level Approach : We will have two Web.config one in ENV-T folder and another in ENV-P folder. Depending upon the machine name we will identify the environment. If it is ENV-T load the Web.Config values from ENV-T folder and if it is ENV-P load the values from ENV-P folder.
Here is the my class :
public static class ConfigurationManager
{
static Configuration _config;
static NameValueCollection nameValueColl;
public static NameValueCollection AppSettings
{
get
{
if (nameValueColl == null)
{
if (_config == null)
_config = LoadConfig();
nameValueColl = new NameValueCollection();
foreach (KeyValueConfigurationElement configElement in _config.AppSettings.Settings)
{
nameValueColl.Add(configElement.Key, configElement.Value);
}
}
return nameValueColl;
}
}
private static Configuration LoadConfig()
{
string basePath = string.Empty;
if (System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath != null)
{
basePath = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
}
string machineName = System.Environment.MachineName;
if (machineName.Equals("MachineA"))
{
_config = WebConfigurationManager.OpenWebConfiguration(basePath + "Test");
}
else if (machineName.ToLower().Equals("MachineB"))
{
_config = WebConfigurationManager.OpenWebConfiguration(basePath + "Prod");
}
return _config;
}
}
Now all i have to do is write
ConfigurationManager.AppSettings["KEY1"]
to read the Appsetting key "KEY1" and i get the correct value for that particular environment.
Question :
I have a key 开发者_StackOverflow
<add key="NoOfRecords" value="50"/>
.
For some reason after several hits ( in a day or two) the value i get for NoOfRecords key is 50,50,50,50,50 instead of 50. Possible reason : If i add a key,value say "NoOfRecords","50" to a NameValueCollection object which Already has "NoOfRecords","50" it will store the value as "NoOfRecords","50,50".
But again how this is possible cause just before this code block i am creating a new object and also i have a null check for this nameValueColl variable.
精彩评论