09-008 Routing 之 DefaultInlineConstraintResolver
Posted on 2015-04-08 17:01 DotNet1010 阅读(179) 评论(0) 收藏 举报核心代码如下:
这个类是解析文本 如 range(5,100) 为具体的约束类 如:RangeRouteConstraint
private readonly IDictionary<string, Type> _inlineConstraintMap;
private readonly IServiceProvider _serviceProvider;
public DefaultInlineConstraintResolver(IServiceProvider serviceProvider,
IOptions<RouteOptions> routeOptions)
{
// 这里是否还记得:
// IOptions<RouteOptions> 默认实现是 OptionManager
// 构造函数是: public OptionsManager(IEnumerable<IConfigureOptions<RouteOptions>> setups)
// 如果没有配置信息 setups 没内容 Get 的时候 默认是 new RouteOptions();
_serviceProvider = serviceProvider;
_inlineConstraintMap = routeOptions.Options.ConstraintMap;
}
/// <inheritdoc />
/// <example>
/// A typical constraint looks like the following
/// "exampleConstraint(arg1, arg2, 12)".
/// Here if the type registered for exampleConstraint has a single constructor with one argument,
/// The entire string "arg1, arg2, 12" will be treated as a single argument.
/// In all other cases arguments are split at comma.
/// </example>
public virtual IRouteConstraint ResolveConstraint([NotNull] string inlineConstraint)
{
string constraintKey;
string argumentString;
var indexOfFirstOpenParens = inlineConstraint.IndexOf('(');
if (indexOfFirstOpenParens >= 0 && inlineConstraint.EndsWith(")", StringComparison.Ordinal))
{
// 有参数的情况 比如:range(5,100)
constraintKey = inlineConstraint.Substring(0, indexOfFirstOpenParens);
argumentString = inlineConstraint.Substring(indexOfFirstOpenParens + 1,
inlineConstraint.Length - indexOfFirstOpenParens - 2);
}
else
{
// 没有参数的情况 比如 int;doube 等
constraintKey = inlineConstraint;
argumentString = null;
}
Type constraintType;
if (!_inlineConstraintMap.TryGetValue(constraintKey, out constraintType))
{
// Cannot resolve the constraint key
return null;
}
// 必须实现接口 IRouteConstraint
if (!typeof(IRouteConstraint).GetTypeInfo().IsAssignableFrom(constraintType.GetTypeInfo()))
{
throw new InvalidOperationException(
Resources.FormatDefaultInlineConstraintResolver_TypeNotConstraint(
constraintType, constraintKey, typeof(IRouteConstraint).Name));
}
// 创建具体的约束对象
return CreateConstraint(constraintType, argumentString);
}
浙公网安备 33010602011771号