QuickConfig
Tijd voor een post over iets wat ik heb gemaakt: QuickConfig, het enige NuGet-package dat ik tot nu toe heb gepubliceerd.
QuickConfig is een kleine library voor configuratie in .NET-apps. Je maakt een class met je instellingen, en QuickConfig regelt het laden en opslaan. Weinig code, geen gedoe.
Ik heb het oorspronkelijk voor mijn eigen hobbyprojecten geschreven. Inmiddels gebruik ik het continu.
Hoe werkt het?
Stap 1: Maak een configuratie-class
Maak een class die erft van ConfigBase en voeg je instellingen toe als properties.
using QuickConfig;
public class Config : ConfigBase
{
public string SettingOne { get; set; }
public string SettingTwo { get; set; }
}
Stap 2: Maak een ConfigManager en laad je config
Maak een ConfigManager en geef hem een naam. Die naam wordt de map waarin je config wordt opgeslagen. In het volledige voorbeeld onderaan gebruik ik de naam van de assembly als map en “Config” als bestandsnaam. Laad daarna de config:
// Replace FolderName with the name of the folder to store the configration in.
// Use System.Reflection.Assembly.GetExecutingAssembly().GetName().Name for the project name.
ConfigManager configManager = new ConfigManager("FolderName");
// Replace ConfigName with the name of the config file within the project.
// A project can have multiple files. Just use Config if you only want one.
Config config = configManager.GetConfig<Config>("ConfigName");
Stap 3: Pas een instelling aan en sla op
Nu kun je je instellingen aanpassen en opslaan:
config.SettingOne = "Test";
if (config.SettingOne == "Test")
{
Console.WriteLine("Config setting was set correctly.");
}
else
{
Console.WriteLine("Config setting was not set correctly.");
}
config.Save();
Volledig voorbeeld
Hier is alles bij elkaar:
using QuickConfig;
public class Config : ConfigBase
{
public string SettingOne { get; set; }
public string SettingTwo { get; set; }
}
public class Program
{
public static void Main()
{
ConfigManager configManager = new ConfigManager(System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
Config config = configManager.GetConfig<Config>("Config");
config.SettingOne = "Test";
if (config.SettingOne == "Test")
{
Console.WriteLine("Config setting was set correctly.");
}
else
{
Console.WriteLine("Config setting was not set correctly.");
}
config.Save();
}
}
