目录
1.2 Initialize a dynamic attribute provider with extra attributes for selected method info
1.3 Get all attributes, attributes returned by extraAttributes factory will have more priority than
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Flatwhite.Core.Provider
{
/// <summary>
/// </summary>
public class DynamicAttributeProvider : IAttributeProvider
{
private readonly IAttributeProvider _original;
private readonly Func<List<Tuple<MethodInfo, Attribute>>> _extraAttributes;
/// <summary>
/// </summary>
/// <param name="original"></param>
/// <param name="extraAttributes"></param>
public DynamicAttributeProvider(IAttributeProvider original, Func<List<Tuple<MethodInfo, Attribute>>> extraAttributes)
{
_original = original;
_extraAttributes = extraAttributes;
}
/// <summary>
/// </summary>
/// <param name="methodInfo"></param>
/// <param name="invocationContext"></param>
/// <returns></returns>
public IEnumerable<Attribute> GetAttributes(MethodInfo methodInfo, IDictionary<string, object> invocationContext)
{
var attributes = _extraAttributes()
.Where(x => x.Item1 == null || x.Item1 == methodInfo)
.Select(x => x.Item2)
.ToList();
var uniqueTypes = attributes
.Select(a => a.GetType())
.Where(type => type.GetCustomAttributes<AttributeUsageAttribute>().Any(x => x.AllowMultiple == false))
.ToList();
var originalAttributes = _original.GetAttributes(methodInfo, invocationContext)
.Where(a => uniqueTypes.All(t => t != a.GetType()));
return originalAttributes.Union(attributes);
}
}
}