Created
April 4, 2017 07:17
-
-
Save MongkonEiadon/d6d54a43535e73f7118539825f70e72b to your computer and use it in GitHub Desktop.
Attribute for to read configuration and the reader to read application setting file (app/web.config)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
public class AppSettingAttribute : Attribute | |
{ | |
public string Name { get; } | |
public string DefaultValue { get; } | |
public AppSettingAttribute(string name) | |
{ | |
Name = name; | |
} | |
public AppSettingAttribute(string name, string defaultValue) | |
{ | |
Name = name; | |
DefaultValue = defaultValue; | |
} | |
} | |
public interface IConfigurationReader | |
{ | |
T Load<T>() where T : class, new(); | |
object Load(Type type); | |
} | |
public class ConfigurationReader : IConfigurationReader { | |
public T Load<T>() where T : class, new() => Load(typeof(T)) as T; | |
public object Load(Type type) | |
{ | |
var instance = Activator.CreateInstance(type); | |
var prop = type.GetProperties().Where(x => x.CustomAttributes.Any(y => y.AttributeType == typeof(AppSettingAttribute))); | |
foreach (var p in prop) | |
{ | |
var appconfig = (AppSettingAttribute)p.GetCustomAttributes(typeof(AppSettingAttribute), true).FirstOrDefault(); | |
if (appconfig != null) | |
{ | |
var value = new System.Configuration.AppSettingsReader().GetValue(appconfig.Name, p.PropertyType) ?? appconfig.DefaultValue; | |
p.SetValue(instance, Convert.ChangeType(value, p.PropertyType), null); | |
} | |
} | |
return instance; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment