This repository has been archived by the owner on Dec 14, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
EnumerableWrapperProvider.cs
76 lines (66 loc) · 2.73 KB
/
EnumerableWrapperProvider.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// 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;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.Extensions.Internal;
namespace Microsoft.AspNetCore.Mvc.Formatters.Xml
{
/// <summary>
/// Provides a <see cref="IWrapperProvider"/> for interface types which implement
/// <see cref="IEnumerable{T}"/>.
/// </summary>
public class EnumerableWrapperProvider : IWrapperProvider
{
private readonly IWrapperProvider _wrapperProvider;
private readonly ConstructorInfo _wrappingTypeConstructor;
/// <summary>
/// Initializes an instance of <see cref="EnumerableWrapperProvider"/>.
/// </summary>
/// <param name="sourceEnumerableOfT">Type of the original <see cref="IEnumerable{T}" />
/// that is being wrapped.</param>
/// <param name="elementWrapperProvider">The <see cref="IWrapperProvider"/> for the element type.
/// Can be null.</param>
public EnumerableWrapperProvider(
Type sourceEnumerableOfT,
IWrapperProvider elementWrapperProvider)
{
if (sourceEnumerableOfT == null)
{
throw new ArgumentNullException(nameof(sourceEnumerableOfT));
}
var enumerableOfT = ClosedGenericMatcher.ExtractGenericInterface(
sourceEnumerableOfT,
typeof(IEnumerable<>));
if (!sourceEnumerableOfT.GetTypeInfo().IsInterface || enumerableOfT == null)
{
throw new ArgumentException(
Resources.FormatEnumerableWrapperProvider_InvalidSourceEnumerableOfT(typeof(IEnumerable<>).Name),
nameof(sourceEnumerableOfT));
}
_wrapperProvider = elementWrapperProvider;
var declaredElementType = enumerableOfT.GenericTypeArguments[0];
var wrappedElementType = elementWrapperProvider?.WrappingType ?? declaredElementType;
WrappingType = typeof(DelegatingEnumerable<,>).MakeGenericType(wrappedElementType, declaredElementType);
_wrappingTypeConstructor = WrappingType.GetConstructor(new[]
{
sourceEnumerableOfT,
typeof(IWrapperProvider)
});
}
/// <inheritdoc />
public Type WrappingType
{
get;
}
/// <inheritdoc />
public object Wrap(object original)
{
if (original == null)
{
return null;
}
return _wrappingTypeConstructor.Invoke(new[] { original, _wrapperProvider });
}
}
}