关于配置文件的目录:[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. dojo/query源码解析

    dojo/query模块是dojo为开发者提供的dom查询接口.该模块的输出对象是一个使用css选择符来查询dom元素并返回NodeList对象的函数.同时,dojo/query模块也是一个插件,开发 ...

  2. 《kali linux 渗透测试初级教程》免费下载

    Kali Linux系列教程是在51cto上售卖的入门教程,售价100元.每天都有很多网友找我要全部教程,也有人偷偷的录制了教程.索性公开出来,如果您觉得还可以的话,希望可以选择发个小红包或者转发 获 ...

  3. [翻译]docker生态圈Mindmap

    Docker是一个开源的Linux容器,其被业界所接受,很快成为了一个产业标准.Docker可以减少应用程序启动 时候的大量资源的筹备.docker很快的成为了新兴的应用程序容器标准.现在有很多项目正 ...

  4. Android Studio 1.0.2项目实战——从一个APP的开发过程认识Android Studio

    Android Studio 1.0.1刚刚发布不久,谷歌紧接着发布了Android Studio 1.0.2版本,和1.0.0一样,是一个Bug修复版本.在上一篇Android Studio 1.0 ...

  5. 【面试必备】javascript的原型和继承

    原型.闭包.作用域等知识可以说是js中面试必考的东西,通过你理解的深度也就能衡量出你基本功是否扎实.今天来复习一下javascript的原型和继承,虽说是老生常谈的话题,但对于这些知识,自己亲手写一遍 ...

  6. 【译】什么导致了Context泄露:Handler&内部类

    思考下面代码 public class SampleActivity extends Activity { private final Handler mLeakyHandler = new Hand ...

  7. 学习Scala第一篇-从hello World开始

    最近开始系统性的学习scala.其实之前使用过scala的,比如我在用Gatling这款性能测试工具的时候就接触到了scala了.Gatling本身就是用Scala写的,而且Gatling的性能测试配 ...

  8. python Web开发框架-Django (2)

    接上篇文章,介绍一些实用的技巧和注意点.首次用MarkDown编辑,感觉行空隙太大,不是那么好看. GET/POST 前后端会有数据交互,使用JQuery来实现get/post请求 GET 方法1:通 ...

  9. 纯js 判断手势滑动方向

    $('body').on('touchstart', '#gallerySlider img', function(e) { var touch = e.originalEvent, startX = ...

  10. [全文检索]Lucene基础入门.

    本打算直接来学习Solr, 现在先把Lucene的只是捋一遍. 本文内容: 1. 搜索引擎的发展史 2. Lucene入门 3. Lucene的API详解 4. 索引调优 5. Lucene搜索结果排 ...