Unity IOC configuration with json - c#

In the app.config, it can look like below and the services and repositories are defined in a different file Unity.config. My question is, is it possible to do below in appsettings.json instead of app.config and Unity.json instead of Unity.config?
app.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="Unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" requirePermission="false" restartOnExternalChanges="true" />
</configSections>
<Unity configSource="Config\Unity.config"/>
<appSettings>
<add key="DateFormat" value="yyyyMMdd"/>
</appSettings>
</configuration>
Unity.config
<Unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="IHelpfulRepository" type="Repositories.IHelpfulRepository, Repositories" />
<alias alias="HelpfulRepository" type="Repositories.Implementation.HelpfulRepository, Repositories" />
</Unity>

no it's not possible. there is a work around.
So what I had to do was make my own UnityContainerExtensions class, load an xml file that looks just like an app.config file, get the unity section, and convert that to a UnityConfigurationSection. code below
MyUnityContainerExtensions.cs
public static class MyUnityContainerExtensions
{
public static IUnityContainer LoadXML(this IUnityContainer container, string xmlFilePath = ".\\Config\\Unity.config")
{
XmlDocument doc = new XmlDocument();
doc.Load(xmlFilePath);
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = xmlFilePath };
Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
UnityConfigurationSection section = (UnityConfigurationSection)configuration.GetSection("unity");
return section.Configure(container, string.Empty);
}
}
Unity.config
<configuration>
<configSections>
<section name="Unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Unity.Configuration" requirePermission="false" restartOnExternalChanges="true" />
</configSections>
<Unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="IHelpfulRepository" type="Repositories.IHelpfulRepository, Repositories" />
<alias alias="HelpfulRepository" type="Repositories.Implementation.HelpfulRepository, Repositories" />
</Unity>
...
</configuration>
Then where I'm loading the unity configuration, I just call the new extension method.
IUnityContainer container = new UnityContainer().LoadXML();

Related

How to retrieve a custom section from an app.config in .NET?

I have a .NET Framework 4.7.2 library project, inside there's an App.config file like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="NewDocumentMetadata" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<NewDocumentMetadata>
<add key="Type" value="principal"/>
<add key="IsActive" value="true"/>
</NewDocumentMetadata>
<appSettings>
<add key="Entity" value="9"/>
<add key="Flux" value="pdf"/>
</appSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<!-- [...] -->
</assemblyBinding>
</runtime>
</configuration>
As you can see, I have some standard settings, but also a custom section. I have no problems with the settings, but when I retrieve the section, it works, but there I'm stuck, when I try to cast it to NameValueCollection or AppSettingsSection it gives me a null value, I'm stuck with a ConfigurationOption object I am not able to work with.
var appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
flux = appConfig.AppSettings.Settings["Flux"].Value; //Works
entity = appConfig.AppSettings.Settings["Entity"].Value; //Works
var metadataSection = appConfig.GetSection("NewDocumentMetadata"); //What do I do with this boy?
I need to retrieve the settings within the NewDocumentMetadata section, how to proceed?
You should try this :
var metadataSection = ConfigurationManager.GetSection("NewDocumentMetadata") as NameValueCollection;
// Get all the value foreach key
foreach(var key in metadataSection.AllKeys)
{
string value = metadataSection.GetValues(key).FirstOrDefault()
}
I just found out that the problem was with this line :
<section name="NewDocumentMetadata" type="System.Configuration.NameValueSectionHandler" />.
I changed the type and went for this :
<section name="NewDocumentMetadata" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
Now I just have to do this kind of code to retrieve the values I want :
var metadataSection = (AppSettingsSection)appConfig.GetSection("NewDocumentMetadata");
foreach (var key in metadataSection.Settings.AllKeys)
{
string value = metadataSection.Settings[key].Value;
}

How to use custom configuration file or app.config in .NET application

I have MVC5 .NET 4.6.1 C# web application
I want to create a custom config file separate from web.config to store some settings my application uses.
I tried to follow this article https://support.microsoft.com/en-us/kb/815786
however the items I set in app.config:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
</system.web>
<appSettings>
<add key="Key0" value="0" />
<add key="Key1" value="1" />
<add key="Key2" value="2" />
</appSettings>
</configuration>
are not seen in my application see , eg. they come as null:
string attr = ConfigurationManager.AppSettings["Key0"];
Why isn't it working? Am I missing something?
Alternatively I would like to create a custom config file eg. mycustom.config to define my global app settings.
EDIT
Solution I used
Follwing this post https://social.msdn.microsoft.com/Forums/vstudio/en-US/11e6d326-c32c-46b1-a9a2-1fbef96f33ee/howto-custom-configuration-files?forum=netfxbcl
In web.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="newAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</configSections>
<newAppSettings file="C:\mycustom.config"/>
</configuration>
Then mycustom.config
<?xml version="1.0" encoding="utf-8" ?>
<newAppSettings>
<add key="OurKey" value="OurValue"/>
</newAppSettings>
And reading the value:
System.Collections.Specialized.NameValueCollection newAppSettings = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("newAppSettings");
string key = Convert.ToDateTime(newAppSettings["OurKey"]);
You can use separate config file for connection strings and app settings:
<appSettings configSource="appSettings.config" />
<connectionStrings configSource="connectionStrings.config"/>
appSettings.config file
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="Setting1" value="App setting 1" />
</appSettings>
connectionStrings.config file
<?xml version="1.0" encoding="utf-8"?>
<connectionStrings>
<add name="MyConnStr1" connectionString="My connection string" />
</connectionStrings>
Usage is same as it was before:
var setting1 = ConfigurationManager.AppSettings["Setting1"];
var connString1 = ConfigurationManager.ConnectionStrings["MyConnStr1"].ConnectionString;
//Helps to open the Root level web.config file.
Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
//Modifying the AppKey from AppValue to AppValue1
webConfigApp.AppSettings.Settings["AppKey"].Value = "AppValue1";
<appSettings>
<add key="AppKey" value="AppValue"/>
</appSettings>

Spring.Net. ContextRegistry.GetContext() exception, cannot configure Common.Logging

I cannot get the IApplication context for my console app
I get an exception with this detail:
The type initializer for 'Spring.Context.Support.ContextRegistry' threw an exception.
With inner exception:
Could not configure Common.Logging from configuration section 'common/logging
There's clearly something basic I've not hooked up, but I'm not sure what.
using Spring.Context;
using Spring.Context.Support;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
IApplicationContext ctx = ContextRegistry.GetContext();
}
}
}
And my app.config looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
</configSections>
<spring>
<context>
<resource uri="config://spring/objects"/>
</context>
<objects xmlns="http://www.springframework.net">
<description>An example that demonstrates simple IoC features. </description>
</objects>
</spring>
</configuration>
Spring.Net uses Common Logging as facility for logging, you have to add the logging configuration to your app.config and the proper library to the referenced assemblies.
<configuration>
<configSections>
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
</configSections>
<common>
<logging>
<factoryAdapter type="Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter, Common.Logging">
<arg key="level" value="DEBUG" />
<arg key="showLogName" value="true" />
<arg key="showDataTime" value="true" />
<arg key="dateTimeFormat" value="yyyy/MM/dd HH:mm:ss:fff" />
</factoryAdapter>
</logging>
</common>
</configuration>
http://netcommon.sourceforge.net/docs/1.2.0/reference/html/logging.html#logging-declarative-config
The type initializer for 'Spring.Context.Support.ContextRegistry'
threw an exception
This is valueable information and Spring.net is really good at providing additional information. Whenever Spring.net throws something, be sure to read the InnerException.
WHen I edit my config I get the messages: Could not find schema
information for the attribute #. for # = 'uri', 'context', 'resource'
and 'spring'
This is normal if you didn't install the schemas. You can download the schemas at their site and find additional information in their docs. Please note that this is optional and spring runs without those schemas.

Storing settings in configFile

Try to save all data in to config file, and then read it and apply to my program during running - as user preference.
Whats done: create new config file (using Add new element-> add congif file). In this file put simple code
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSetting>
<add Key="Volume" value="100" />
</appSetting>
</configuration>
After it create method
public int GetVolumeFromConfigFile()
{
return Convert.ToInt32(ConfigurationManager.AppSettings.Get("Volume"));
}
and in main programm call it like
Value = (MyClass.GetVolumeFromConfigFile());
But it's not work. (During debaggin it's return nothing)
Think it can be few reason:
I need to add (I don't now in what way) what config file to use, because i have few files *.config - one as default (App.exe.config, and another - that i created)
I use incorrect method to get value from config file
Also I read about some another way to store app settings, like store it in *.settings file
What I'm doing wrong and what method prefered?
Additional information - use net 4.0
EDIT
Remove my config file, and add to existed few lines (in strong>)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="PlayDemo.SettingsPlayIt" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<userSettings>
<PlayDemo.SettingsPlayIt>
<setting name="Volume" serializeAs="String">
<value>10</value>
</setting>
</PlayDemo.SettingsPlayIt>
</userSettings>
Here I add my key
<appSetting>
<add key="Volume" value="100" />
</appSetting>
</configuration>
try this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Volume" value="100" />
</appSettings>
</configuration>
and
return Convert.ToInt32(ConfigurationManager.AppSettings["Volume"]);
the appSettings are key value pairs, so you can access it like you would a value in a Dictionary
If you want to use a separate config file, try this:
Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
config.AppSettings.File = "yourFileName"'tell Configuration what file to read
config.Save(ConfigurationSaveMode.Modified) ' save the Configuration setting
ConfigurationManager.RefreshSection("appSettings") ' update just the <appSettings> node
I really like the following technique, using ConfigurationSection. This allows you for painless manipulation of your configuration. But it is more specific upfront.
http://msdn.microsoft.com/en-us/library/2tw134k3%28v=vs.90%29.aspx

Reading keyvalue pairs into dictionary from app.config configSection

I currently have an app.config in an application of mine set up like so:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="DeviceSettings">
<section name="MajorCommands" type="System.Configuration.DictionarySectionHandler"/>
</sectionGroup>
</configSections>
<appSettings>
<add key="ComPort" value="com3"/>
<add key="Baud" value="9600"/>
<add key="Parity" value="None"/>
<add key="DataBits" value="8"/>
<add key="StopBits" value="1"/>
<add key="Ping" value="*IDN?"/>
<add key="FailOut" value="1"/>
</appSettings>
<DeviceSettings>
<MajorCommands>
<add key="Standby" value="STBY"/>
<add key="Operate" value="OPER"/>
<add key="Remote" value="REMOTE"/>
<add key="Local" value="LOCAL"/>
<add key="Reset" value="*RST" />
</MajorCommands>
</DeviceSettings>
</configuration>
My current objective is to foreach or simply read all values from MajorCommands into a Dictionary<string, string> formatted as Dictionary<key, value>. I've tried several different approaches using System.Configuration but none seem to work and I haven't been able to find any details out there for my exact question. Is there any proper way to do this?
using ConfigurationManager class you can get whole section from app.config file as Hashtable which you can convert to Dictionary if you want to:
var section = (ConfigurationManager.GetSection("DeviceSettings/MajorCommands") as System.Collections.Hashtable)
.Cast<System.Collections.DictionaryEntry>()
.ToDictionary(n=>n.Key.ToString(), n=>n.Value.ToString());
you'll need to add reference to System.Configuration assembly
You are almost there - you just have nested your MajorCommands a level too deep. Just change it to this:
<configuration>
<configSections>
<section
name="MajorCommands"
type="System.Configuration.DictionarySectionHandler" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<MajorCommands>
<add key="Standby" value="STBY"/>
<add key="Operate" value="OPER"/>
<add key="Remote" value="REMOTE"/>
<add key="Local" value="LOCAL"/>
<add key="Reset" value="*RST" />
</MajorCommands>
</configuration>
And then the following will work for you:
var section = (Hashtable)ConfigurationManager.GetSection("MajorCommands");
Console.WriteLine(section["Reset"]);
Note that this is a Hashtable (not type safe) as opposed to a Dictionary. If you want it to be Dictionary<string,string> you can convert it like so:
Dictionary<string,string> dictionary = section.Cast<DictionaryEntry>().ToDictionary(d => (string)d.Key, d => (string)d.Value);
I would probably treat the config file as an xml file.
Dictionary<string, string> myDictionary = new Dictionary<string, string>();
XmlDocument document = new XmlDocument();
document.Load("app.config");
XmlNodeList majorCommands = document.SelectNodes("/configuration/DeviceSettings/MajorCommands/add");
foreach (XmlNode node in majorCommands)
{
myDictionary.Add(node.Attributes["key"].Value, node.Attributes["value"].Value)
}
If document.Load doen't work, try converting your config file to xml file.

Categories

Resources