关于配置文件的目录:[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)的更多相关文章

  1. C#/ASP.NET应用程序配置文件app.config/web.config的增、删、改操作,无法为请求的 Configuration 对象创建配置文件。

    应用程序配置文件,对于asp.net是 web.config,对于WINFORM程序是 App.Config(ExeName.exe.config). 配置文件,对于程序本身来说,就是基础和依据,其本 ...

  2. [Asp.net 5] Configuration-新一代的配置文件

    微软新一代asp.net(vnext),也叫asp.net 5,开源代码都放在网址https://github.com/aspnet下. 本文介绍的是Configuration工程,下载路径为http ...

  3. [Asp.net 5] Configuration-新一代的配置文件(接口定义与基础实现)

    关于配置文件的目录:[Asp.net 5] Configuration-新一代的配置文件 本系列文章讲的是asp.net 5(Asp.net VNext)中的配置文件部分,工程下载地址为:https: ...

  4. [Asp.net 5] Configuration-新一代的配置文件(ConfigurationSource的多种实现)

    关于配置文件的目录:[Asp.net 5] Configuration-新一代的配置文件 在前面我们介绍了,系统中用IConfigurationSource表示不同配置文件的来源,起到读取.设置.加载 ...

  5. Asp.net Core 和类库读取配置文件信息

    Asp.net Core 和类库读取配置文件信息 看干货请移步至.net core 读取配置文件公共类 首先开一个脑洞,Asp.net core 被使用这么长时间了,但是关于配置文件(json)的读取 ...

  6. 无法为请求的 Configuration 对象创建配置文件 错误原因

    Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); 无法为请求的 Configura ...

  7. [译]ASP.NET 5 Configuration

    原文:https://docs.asp.net/en/latest/fundamentals/configuration.html ASP.NET 5支持多种配置选项. 应用的配置文件可以是JSON, ...

  8. ASP.NET网站开发中的配置文件

    来源:微信公众号CodeL 1.配置文件层次分类 Machine.config:  对.netframework整体的配置 web.config(framework目录下):  对所有项目所公有的应用 ...

  9. Asp .Net Core 读取appsettings.json配置文件

         Asp .Net Core 如何读取appsettings.json配置文件?最近也有学习到如何读取配置文件的,主要是通过 IConfiguration,以及在Program中初始化完成的. ...

随机推荐

  1. 【读书笔记】.Net并行编程高级教程(二)-- 任务并行

    前面一篇提到例子都是数据并行,但这并不是并行化的唯一形式,在.Net4之前,必须要创建多个线程或者线程池来利用多核技术.现在只需要使用新的Task实例就可以通过更简单的代码解决命令式任务并行问题. 1 ...

  2. C#Light Everywhere

    C#语法嵌入式脚本,0.1Beta版本咯,可用于各种环境,欢迎测试. 可以解决各种热更新问题 比如Unity在AOT环境下,比如各种不能采用动态加载DLL的场合. 如果遇到bug,请给我留言,我会从速 ...

  3. C#并行编程-PLINQ:声明式数据并行

    目录 C#并行编程-相关概念 C#并行编程-Parallel C#并行编程-Task C#并行编程-并发集合 C#并行编程-线程同步原语 C#并行编程-PLINQ:声明式数据并行 背景 通过LINQ可 ...

  4. PHP 基础

    var_dump(empty($a));    判断变量是否为空 var_dump(isset($a));      判断变量是否定义 $a=10;unset($a);      删除变量 var_d ...

  5. fir.im Weekly - 如何打造 Github 「爆款」开源项目

    最近 Android 转用 Swift 的传闻甚嚣尘上,Swift 的 Github 主页上已经有了一次 merge>>「Port to Android」,让我们对 Swift 的想象又多 ...

  6. Sublime Text配置Python开发利器

    Sublime Text配置Python开发利器 收好了 自动提示 jedi 代码格式化 Python PEP8 autoformat 如果还需要在shell中搞搞研究的话,ipython将是很好的选 ...

  7. 深入理解PHP内核(五)函数的内部结构

    php的函数包括用户定义的函数.内部函数(print_r count...).匿名函数.变量函数($func = 'print_r'; $func(array('a','b'));) PHP内核源码中 ...

  8. struts2拦截器

    一.自定义拦截器 struts2拦截器类似于servlet过滤器 首先定义一个拦截器这个拦截器实现了Interceptor接口: package cn.orlion.interceptor; impo ...

  9. 了解HTML表单之input元素的23种type类型

    目录 传统类型 text password file radio checkbox hidden button image reset submit 新增类型 color tel email url ...

  10. NYOJ 1023 还是回文(DP,花最少费用形成回文串)

    /* 题意:给出一串字符(全部是小写字母),添加或删除一个字符,都会产生一定的花费. 那么,将字符串变成回文串的最小花费是多少呢? 思路:如果一个字符串增加一个字符 x可以形成一个回文串,那么从这个字 ...