// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Web.Http.Controllers; namespace System.Web.Http.ModelBinding { /// /// Collection of functions that can produce a parameter binding for a given parameter. /// public class ParameterBindingRulesCollection : Collection> { // Helper to wrap the lambda in a type-check // This is for convenience overloads that want to register by type, which should be a common case. private static Func TypeCheck(Type type, Func func) { return (param => (param.ParameterType == type) ? func(param) : null); } /// /// Adds function to the end of the collection. /// The function added is a wrapper around funcInner that checks that parameterType matches typeMatch. /// /// type to match against HttpParameterDescriptor.ParameterType /// inner function that is invoked if type match succeeds public void Add(Type typeMatch, Func funcInner) { Add(TypeCheck(typeMatch, funcInner)); } /// /// Insert a function at the specified index in the collection. /// /// The function added is a wrapper around funcInner that checks that parameterType matches typeMatch. /// /// index to insert at. /// type to match against HttpParameterDescriptor.ParameterType /// inner function that is invoked if type match succeeds public void Insert(int index, Type typeMatch, Func funcInner) { Insert(index, TypeCheck(typeMatch, funcInner)); } /// /// Execute each binding function in order until one of them returns a non-null binding. /// /// parameter to bind. /// the first non-null binding produced for the parameter. Of null if no binding is produced. public HttpParameterBinding LookupBinding(HttpParameterDescriptor parameter) { foreach (Func func in this) { HttpParameterBinding binding = func(parameter); if (binding != null) { return binding; } } return null; } } }