57 lines
2.0 KiB
C#
57 lines
2.0 KiB
C#
using System.Reflection;
|
|
using Voile.Common.Configuration;
|
|
using Voile.Common.Logging;
|
|
|
|
namespace Voile.Common.Reflection;
|
|
|
|
public class Autoconfigurer
|
|
{
|
|
private static Autoconfigurer instance;
|
|
private static VoileLogger logger = VoileLogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name);
|
|
private Autoconfigurer()
|
|
{
|
|
}
|
|
|
|
public static Autoconfigurer GetInstance()
|
|
{
|
|
if (instance == null)
|
|
{
|
|
instance = new Autoconfigurer();
|
|
}
|
|
return instance;
|
|
}
|
|
|
|
public void Autoconfigure(IConfigurationSource source, string categoryName, object target)
|
|
{
|
|
Type type = target.GetType();
|
|
PropertyInfo[] propertyInfos = type.GetProperties();
|
|
|
|
foreach (PropertyInfo propertyInfo in propertyInfos)
|
|
{
|
|
AutoconfigurableAttribute? autoconfigurableAttribute = propertyInfo.GetCustomAttribute<AutoconfigurableAttribute>();
|
|
if (autoconfigurableAttribute == null)
|
|
continue;
|
|
|
|
Type propertyInfoPropertyType = propertyInfo.PropertyType;
|
|
switch (propertyInfoPropertyType.Name)
|
|
{
|
|
case "Boolean":
|
|
bool booleanValue = source.ReadValue(categoryName, propertyInfo.Name, false);
|
|
propertyInfo.SetValue(target, booleanValue, null);
|
|
break;
|
|
case "Int32":
|
|
int intValue = source.ReadValue(categoryName, propertyInfo.Name, 0);
|
|
propertyInfo.SetValue(target, intValue, null);
|
|
break;
|
|
case "String":
|
|
string stringValue = source.ReadValue(categoryName, propertyInfo.Name, string.Empty);
|
|
propertyInfo.SetValue(target, stringValue, null);
|
|
break;
|
|
default:
|
|
logger.Error("Don't know how to autoconfigure an {0}.", propertyInfoPropertyType.Name);
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
}
|