[Asp.net 5] Configuration-新一代的配置文件(神奇的Binder)
关于配置文件的目录:[Asp.net 5] Configuration-新一代的配置文件
之前看过MVC4.0的源码,里面就有Binder。作用是将前台页面传递过来的键值对/字典表绑定到特定的对象。此处的Binder几乎是同样的作用——将IConfiguration映射为特定的类型<T>.
我们进入正文之前还是看一个例子比较好,这样能充分了解Binder。
public class ComplexOptions
{
public ComplexOptions()
{
Virtual = "complex";
}
public int Integer { get; set; }
public bool Boolean { get; set; }
public virtual string Virtual { get; set; }
} public class Test
{
public IConfiguration BuildConfiguration()
{
var dic = new Dictionary<string, string>
{
{"Integer", "-2"},
{"Boolean", "TRUe"},
{"Nested:Integer", ""}
};
var builder = new ConfigurationBuilder(new MemoryConfigurationSource(dic));
return config = builder.Build();
}
public void BinderTest()
{
var config = BuildConfiguration();
var options = ConfigurationBinder.Bind<ComplexOptions>(config);
Assert.True(options.Boolean);
Assert.Equal(-, options.Integer);
}
}
上面例子比较简单,实际上对象可能是复合对象(对象的属性还是对象),也可能是数组、枚举、结构体等。所以我们创建的过程中需要对属性遍历,如果是复合对象,还涉及到递归的过程,所以我把整个过程绘制成类似流程图的图标。如下图所示:
下面我们正式介绍工程的源码,按照惯例还是上工程结构图(就那么一个文件,搞什么搞)
整个工程只有ConfigurationBinder这一个类,调用过程上面“流程图”已经画出来了。
public static class ConfigurationBinder
{
public static TModel Bind<TModel>(IConfiguration configuration) where TModel : new()
{
var model = new TModel();
Bind(model, configuration);
return model;
} public static void Bind(object model, IConfiguration configuration)
{
if (model == null)
{
return;
} BindObjectProperties(model, configuration);
} private static void BindObjectProperties(object obj, IConfiguration configuration)
{
foreach (var property in GetAllProperties(obj.GetType().GetTypeInfo()))
{
BindProperty(property, obj, configuration);
}
} private static void BindProperty(PropertyInfo property, object propertyOwner, IConfiguration configuration)
{
configuration = configuration.GetConfigurationSection(property.Name); if (property.GetMethod == null || !property.GetMethod.IsPublic)
{
// We don't support set only properties
return;
} var propertyValue = property.GetValue(propertyOwner);
var hasPublicSetter = property.SetMethod != null && property.SetMethod.IsPublic; if (propertyValue == null && !hasPublicSetter)
{
// Property doesn't have a value and we cannot set it so there is no
// point in going further down the graph
return;
} propertyValue = BindType(
property.PropertyType,
propertyValue,
configuration); if (propertyValue != null && hasPublicSetter)
{
property.SetValue(propertyOwner, propertyValue);
}
} private static object BindType(Type type, object typeInstance, IConfiguration configuration)
{
var configValue = configuration.Get(null);
var typeInfo = type.GetTypeInfo(); if (configValue != null)
{
// Leaf nodes are always reinitialized
return CreateValueFromConfiguration(type, configValue, configuration);
}
else
{
var subkeys = configuration.GetConfigurationSections();
if (subkeys.Count() != )
{
if (typeInstance == null)
{
if (typeInfo.IsInterface || typeInfo.IsAbstract)
{
throw new InvalidOperationException(Resources.FormatError_CannotActivateAbstractOrInterface(type));
} bool hasParameterlessConstructor = typeInfo.DeclaredConstructors.Any(ctor => ctor.IsPublic && ctor.GetParameters().Length == );
if (!hasParameterlessConstructor)
{
throw new InvalidOperationException(Resources.FormatError_MissingParameterlessConstructor(type));
} try
{
typeInstance = Activator.CreateInstance(type);
}
catch (Exception ex)
{
throw new InvalidOperationException(Resources.FormatError_FailedToActivate(type), ex);
}
} var collectionInterface = GetGenericOpenInterfaceImplementation(typeof(IDictionary<,>), type);
if (collectionInterface != null)
{
// Dictionary
BindDictionary(typeInstance, collectionInterface, configuration);
}
else
{
collectionInterface = GetGenericOpenInterfaceImplementation(typeof(ICollection<>), type);
if (collectionInterface != null)
{
// ICollection
BindCollection(typeInstance, collectionInterface, configuration);
}
else
{
// Something else
BindObjectProperties(typeInstance, configuration);
}
}
}
return typeInstance;
}
} private static void BindDictionary(object dictionary, Type iDictionaryType, IConfiguration configuration)
{
var iDictionaryTypeInfo = iDictionaryType.GetTypeInfo(); // It is guaranteed to have a two and only two parameters
// because this is an IDictionary<K,V>
var keyType = iDictionaryTypeInfo.GenericTypeArguments[];
var valueType = iDictionaryTypeInfo.GenericTypeArguments[]; if (keyType != typeof(string))
{
// We only support string keys
return;
} var addMethod = iDictionaryTypeInfo.GetDeclaredMethod("Add");
var subkeys = configuration.GetConfigurationSections().ToList(); foreach (var keyProperty in subkeys)
{
var keyConfiguration = keyProperty.Value; var item = BindType(
type: valueType,
typeInstance: null,
configuration: keyConfiguration);
if (item != null)
{
addMethod.Invoke(dictionary, new[] { keyProperty.Key, item });
}
}
} private static void BindCollection(object collection, Type iCollectionType, IConfiguration configuration)
{
var iCollectionTypeInfo = iCollectionType.GetTypeInfo(); // It is guaranteed to have a one and only one parameter
// because this is an ICollection<T>
var itemType = iCollectionTypeInfo.GenericTypeArguments[]; var addMethod = iCollectionTypeInfo.GetDeclaredMethod("Add");
var subkeys = configuration.GetConfigurationSections().ToList(); foreach (var keyProperty in subkeys)
{
var keyConfiguration = keyProperty.Value; try
{
var item = BindType(
type: itemType,
typeInstance: null,
configuration: keyConfiguration);
if (item != null)
{
addMethod.Invoke(collection, new[] { item });
}
}
catch
{
}
}
} private static object CreateValueFromConfiguration(Type type, string value, IConfiguration configuration)
{
var typeInfo = type.GetTypeInfo(); if (typeInfo.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
return CreateValueFromConfiguration(Nullable.GetUnderlyingType(type), value, configuration);
} var configurationValue = configuration.Get(key: null); try
{
if (typeInfo.IsEnum)
{
return Enum.Parse(type, configurationValue);
}
else
{
return Convert.ChangeType(configurationValue, type);
}
}
catch (Exception ex)
{
throw new InvalidOperationException(Resources.FormatError_FailedBinding(configurationValue, type), ex);
}
} private static Type GetGenericOpenInterfaceImplementation(Type expectedOpenGeneric, Type actual)
{
var interfaces = actual.GetTypeInfo().ImplementedInterfaces;
foreach (var interfaceType in interfaces)
{
if (interfaceType.GetTypeInfo().IsGenericType &&
interfaceType.GetGenericTypeDefinition() == expectedOpenGeneric)
{
return interfaceType;
}
} return null;
} private static IEnumerable<PropertyInfo> GetAllProperties(TypeInfo type)
{
var allProperties = new List<PropertyInfo>(); do
{
allProperties.AddRange(type.DeclaredProperties);
type = type.BaseType.GetTypeInfo();
}
while (type != typeof(object).GetTypeInfo()); return allProperties;
}
}
ConfigurationBinder
我们对其中几个方法,进行简单的说明:
- GetAllProperties。系统获取属性的时候,不光要获取当前类的属性也要获取基类的属性。
- 绑定属性时,将需要被绑定的对象作为参数传入进去,由于是引用类型,所以不用返回值也能更改其属性、类似的还有ArrayList等。
- BindProperty(PropertyInfo property, object propertyOwner, IConfiguration configuration)。此处的propertyOwner值会被调用方法中修改。
- 将字符串转换成枚举的方法:
- Enum.Parse(type, configurationValue);、
- 将对象转变类型的方法:
- Convert.ChangeType(configurationValue, type);
- 判断泛型的方法
-
private static Type GetGenericOpenInterfaceImplementation(Type expectedOpenGeneric, Type actual)
{
var interfaces = actual.GetTypeInfo().ImplementedInterfaces;
foreach (var interfaceType in interfaces)
{
if (interfaceType.GetTypeInfo().IsGenericType &&
interfaceType.GetGenericTypeDefinition() == expectedOpenGeneric)
{
return interfaceType;
}
} return null;
}
-
[Asp.net 5] Configuration-新一代的配置文件(神奇的Binder)的更多相关文章
- C#/ASP.NET应用程序配置文件app.config/web.config的增、删、改操作,无法为请求的 Configuration 对象创建配置文件。
应用程序配置文件,对于asp.net是 web.config,对于WINFORM程序是 App.Config(ExeName.exe.config). 配置文件,对于程序本身来说,就是基础和依据,其本 ...
- [Asp.net 5] Configuration-新一代的配置文件
微软新一代asp.net(vnext),也叫asp.net 5,开源代码都放在网址https://github.com/aspnet下. 本文介绍的是Configuration工程,下载路径为http ...
- [Asp.net 5] Configuration-新一代的配置文件(接口定义与基础实现)
关于配置文件的目录:[Asp.net 5] Configuration-新一代的配置文件 本系列文章讲的是asp.net 5(Asp.net VNext)中的配置文件部分,工程下载地址为:https: ...
- [Asp.net 5] Configuration-新一代的配置文件(ConfigurationSource的多种实现)
关于配置文件的目录:[Asp.net 5] Configuration-新一代的配置文件 在前面我们介绍了,系统中用IConfigurationSource表示不同配置文件的来源,起到读取.设置.加载 ...
- Asp.net Core 和类库读取配置文件信息
Asp.net Core 和类库读取配置文件信息 看干货请移步至.net core 读取配置文件公共类 首先开一个脑洞,Asp.net core 被使用这么长时间了,但是关于配置文件(json)的读取 ...
- 无法为请求的 Configuration 对象创建配置文件 错误原因
Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); 无法为请求的 Configura ...
- [译]ASP.NET 5 Configuration
原文:https://docs.asp.net/en/latest/fundamentals/configuration.html ASP.NET 5支持多种配置选项. 应用的配置文件可以是JSON, ...
- ASP.NET网站开发中的配置文件
来源:微信公众号CodeL 1.配置文件层次分类 Machine.config: 对.netframework整体的配置 web.config(framework目录下): 对所有项目所公有的应用 ...
- Asp .Net Core 读取appsettings.json配置文件
Asp .Net Core 如何读取appsettings.json配置文件?最近也有学习到如何读取配置文件的,主要是通过 IConfiguration,以及在Program中初始化完成的. ...
随机推荐
- Java多线程4:synchronized锁机制
脏读 一个常见的概念.在多线程中,难免会出现在多个线程中对同一个对象的实例变量进行并发访问的情况,如果不做正确的同步处理,那么产生的后果就是"脏读",也就是取到的数据其实是被更改过 ...
- comet在asp.net中的实现
网上有关“服务器推送”的介绍非常多,其中一种实现方式就是采用comet技术,在浏览器与服务端之间建立一个http协议的“长连接”,所谓“长连接”,就是指浏览器到服务端的http请求不会马上得到服务端的 ...
- 谈谈javascript语法里一些难点问题(二)
3) 作用域链相关的问题 作用域链是javascript语言里非常红的概念,很多学习和使用javascript语言的程序员都知道作用域链是理解javascript里很重要的一些概念的关键,这些概 ...
- [ZigBee] 7、ZigBee之UART剖析(ONLY串口发送)
综述:USART0和USART1是串行通信接口,它们能够分别运行于异步UART模式或者同步SPI 模式.两个USART具有同样的功能,可以设置在单独的I/O 引脚. 1.UART 模式 UART 模式 ...
- mac 命令行批量删除.svn[转]
mac下.svn是隐藏文件,而且即使我们调成可见的,一个一个删也很麻烦.今天正好同事问起来这个命令,于是想可能有些人也需要,于是还是放到博客里吧 命令比较简单,其实就是一条linux命令,打开终端,首 ...
- bitmap算法
概述 所谓bitmap就是用一个bit位来标记某个元素对应的value,而key即是这个元素.由于采用bit为单位来存储数据,因此在可以大大的节省存储空间 算法思想 32位机器上,一个整形,比如int ...
- ios UIView autoresizingSubview 属性
自动尺寸调整行为 当您改变视图的边框矩形时,其内嵌子视图的位置和尺寸往往也需要改变,以适应原始视图的新尺寸.如果视图的autoresizesSubviews属性声明被设置为YES,则其子视图会根据au ...
- Nginx+Keepalived(带Nginx监控脚本)
转载于:http://www.itxuexiwang.com/a/liunxjishu/2016/0220/151.html?1456381460 Keepalived+ nginx的安装部署 主机: ...
- Atitit.java expression fsm 表达式词法分析引擎 v2 qaa.docx
Atitit.java expression fsm 表达式词法分析引擎 v2 qaa.docx C:\0workspace\AtiPlatf_cms\src\com\attilax\fsm\Java ...
- cordova添加platform
cordova添加platform 一般需要指定版本的 cordova platform add android@4.1