RealSense.DomainBasedConfig 1.1.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package RealSense.DomainBasedConfig --version 1.1.0
NuGet\Install-Package RealSense.DomainBasedConfig -Version 1.1.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="RealSense.DomainBasedConfig" Version="1.1.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add RealSense.DomainBasedConfig --version 1.1.0
#r "nuget: RealSense.DomainBasedConfig, 1.1.0"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install RealSense.DomainBasedConfig as a Cake Addin
#addin nuget:?package=RealSense.DomainBasedConfig&version=1.1.0

// Install RealSense.DomainBasedConfig as a Cake Tool
#tool nuget:?package=RealSense.DomainBasedConfig&version=1.1.0

How to use

  1. Add the following section to your .config file
<configuration>
	<configSections>
		<section name="domainBasedConfig" type="RealSense.DomainBasedConfig.DomainBasedConfigSection, RealSense.DomainBasedConfig" allowLocation="true" allowDefinition="Everywhere" />
	</configSections>
</configuration>
  1. Add the following section to your .config file
<configuration>
	<domainBasedConfig>
		<domains>
			<add domain="localhost" port="3000" map="DevEnv" />
			<add domain="test1.example.com" map="Test1Env" />
			<add domain="example.com" map="LiveEnv" />
			<add domain="www.example.com" map="LiveEnv" />
		</domains>
		<environments>
			<add name="DevEnv">
				<database server="(local)" database="Dev1" />
				<settings>
					<add name="Setting1" value="Apple" />
					<add name="Setting2" value="Cheese" />
				</settings>
			</add>
			<add name="Test1Env">
				<database server="(local)" database="Test1" />
				<settings>
					<add name="Setting1" value="Grape" />
					<add name="Setting2" value="Egg" />
				</settings>
			</add>
			<add name="LiveEnv">
				<database server="(local)\MSSQL2020" database="LiveDatabase" />
				<settings>
					<add name="Setting1" value="Plum" />
					<add name="Setting2" value="Date" />
				</settings>
			</add>
		</environments>
</configuration>

NOTE: The <domains> section is only required for Web Applications and provides automatic resolution of which environment to use based on the HttpContext.Request details. For console applications (for example) you can request settings and connection strings by stating the environment name.

  1. Access to a connection string from Entity Framework is done adding a new partial class that implements a static method as follows:
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Web;

	namespace WebService
	{
		public partial class MyEntities
		{
			/// <summary>
			/// Initializes a new instance using a modified connection string 
			/// based on host name.
			/// </summary>
			public static MyEntities CreateDomainBased()
			{
				string s = RealSense.DomainBasedConfig.Instance.GetHttpConnectionString("MyEntities");
				return new MyEntities(s);
			}
		}
	}
  1. Change your Entity Framework instantiation from
	using (var ctx = new MyEntities())
	{
	}
TO:
	using (var ctx = MyEntities.CreateDomainBased())
	{
	}

Example Application

// Program.cs
using Inst = RealSense.DomainBasedConfig.Instance;
using Debug = System.Diagnostics.Debug;

namespace TestDomainBasedConfig
{
	internal class Program
	{
		private static void Main(string[] args)
		{
			Debug.WriteLine("1) Dump Config");
			Debug.WriteLine(Inst.DumpConfig());

			Debug.WriteLine("2) Get Environment (valid)");
			var env1 = Inst.GetEnvironment("Dev2Env");
			Debug.WriteLine(env1);

			Debug.WriteLine("3) Get Configuration String \"Stock\" under \"Dev2Env\"");
			Debug.WriteLine(Inst.GetEnvConnectionString("Stock", "Dev2Env"));

			Debug.WriteLine("4) Get Setting from Environment (env1) (will throw if setting doesn't exist)");
			var v1 = env1.Settings["Setting1"];
			Debug.Assert(v1 == "Strawberry");
			Debug.WriteLine($"Setting1=\"{v1}\" under \"{env1.Name}\" environment..");

			Debug.WriteLine("5) Safely get non-existant Setting from Environment (env1) (returns provided defaultValue or null if doesn't exist)");
			var value2 = env1.Settings.Get("Setting2");
			Debug.Assert(value2 == null);
			t = value2 ?? "(null)";
			Debug.WriteLine($"Setting Setting2: {t}");

			Debug.WriteLine("7) Get Environment based on HttpContext");
			// NOTE: will throw for non-web applications as HttpContext.Current will be null
			try
			{
				var env3 = Inst.GetEnvironmentFromHttp();
				Debug.Assert(env3 != null);
			}
			catch (RealSense.DomainBasedConfig.NonHttpEnvironmentException ex)
			{
				Debug.WriteLine(ex.Message);
			}

			Debug.WriteLine("8) Get Connection String based on HttpContext");
			// NOTE: This will throw for non-web applications as HttpContext.Current will be null
			try
			{
				var connString2 = Inst.GetHttpConnectionString("HumanResources");
				Debug.Assert(connString2 != null);
			}
			catch (RealSense.DomainBasedConfig.NonHttpEnvironmentException ex)
			{
				Debug.WriteLine(ex.Message);
			}

			Debug.WriteLine("9) Enumerate settings in an environment");
			Debug.WriteLine($"Settings for {env1.Name} environment:");
			foreach(var setting in env1.Settings)
				Debug.WriteLine($" - {setting.Key} => {setting.Value}");
			Debug.WriteLine($"Settings for Test1Env environment:");
			foreach(var setting in Inst.GetEnvironment("Test1Env").Settings)
				Debug.WriteLine($" - {setting.Key} => {setting.Value}");

			Debug.WriteLine("10) Enumerate all Settings for all Environments");
			Debug.WriteLine($"Enumerate all settings:");
			foreach (var env in Inst.GetConfig().Environments)
			{
				Debug.WriteLine($" - Environment: {env.Key}");
				foreach (var setting in env.Value.Settings)
					Debug.WriteLine($" - - {setting.Key} => {setting.Value}");
			}

			Debug.WriteLine("11) Enumerate all Connection Strings for all Environments");
			var csList = new string[] { "Stock", "Marketing", "HumanResources", "Development" };
			Debug.WriteLine($"Enumerate all connection strings:");
			foreach (var env in Inst.GetConfig().Environments)
			{
				var db = env.Value.Database;
				Debug.WriteLine($" - Environment: {env.Key}; Database: {db}");
				foreach (var cs in csList)
				{
					var str = Inst.GetEnvConnectionString(cs, env.Key);
					Debug.WriteLine($" - - {cs} => {str}");
				}
			}
		}
	}
}
// App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<configSections>
		<section name="domainBasedConfig" type="RealSense.DomainBasedConfig.DomainBasedConfigSection, RealSense.DomainBasedConfig" allowLocation="true" allowDefinition="Everywhere" />
	</configSections>
	<startup>
		<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
	</startup>
	<connectionStrings>
		<remove name="LocalSqlServer" />
		<add name="Stock" connectionString="Data Source=xxxxxxx;Initial Catalog=xxxxxxx;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
		<add name="HumanResources" connectionString="metadata=res://HumanResources/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=xxxxxxx;Initial Catalog=xxxxxxx;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
	</connectionStrings>
	<domainBasedConfig>
		<domains>
			<add domain="localhost" port="3000" map="Dev1Env" />
			<add domain="example.com" map="LiveEnv" />
			<add domain="www.example.com" map="LiveEnv" />
		</domains>
		<environments>
			<add name="Dev1Env">
				<database server="(local)" database="Dev2Database" />
				<settings>
					<add name="Setting1" value="Strawberry" />
					<add name="Setting2" value="Pear" />
				</settings>
			</add>
			<add name="LiveEnv">
				<database server="(local)\MSSQL2020" database="LiveDatabase" />
				<settings>
					<add name="Setting1" value="Plum" />
					<add name="Setting2" value="Date" />
				</settings>
			</add>
		</environments>
	</domainBasedConfig>
</configuration>
Product Compatible and additional computed target framework versions.
.NET Framework net46 is compatible.  net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

This package has no dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.5.0 399 9/7/2021
1.4.0 348 9/7/2021
1.3.0 340 4/17/2021
1.2.0 578 8/13/2019
1.1.0 702 12/4/2018
1.0.0 910 8/16/2017