Skip to content

Instantly share code, notes, and snippets.

@alistair
Created April 16, 2015 21:39
Show Gist options
  • Select an option

  • Save alistair/6a14a4ca8f9a2fb594eb to your computer and use it in GitHub Desktop.

Select an option

Save alistair/6a14a4ca8f9a2fb594eb to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
public interface ICache<in T, out TOut>
{
TOut Get(T key);
}
public class Cache<T, TOut> : ICache<T, TOut>
{
private readonly Func<T, TOut> _populator;
public readonly ConcurrentDictionary<T, TOut> _cache;
public Cache(Func<T, TOut> populator, IEqualityComparer<T> comparer )
{
_populator = populator;
_cache = new ConcurrentDictionary<T, TOut>(comparer);
}
public TOut Get(T key)
{
return _cache.GetOrAdd(key, _populator);
}
}
public class ActionDescriptorComparer : EqualityComparer<HttpActionDescriptor>
{
public override bool Equals(HttpActionDescriptor x, HttpActionDescriptor y)
{
return x.ActionName == y.ActionName && x.ControllerDescriptor.ControllerType == y.ControllerDescriptor.ControllerType;
}
public override int GetHashCode(HttpActionDescriptor obj)
{
return 1; // do this properly
}
}
public class MyAttribute : Attribute
{
public string SomeValue { get; set; }
}
public class OnAttributeAttribute<TOut> : ActionFilterAttribute
{
private readonly ICache<HttpActionDescriptor, TOut> _cache;
private readonly Action<TOut> _action;
public OnAttributeAttribute(ICache<HttpActionDescriptor, TOut> cache, Action<TOut> action)
{
_cache = cache;
_action = action;
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
_action(_cache.Get(actionContext.ActionDescriptor));
base.OnActionExecuting(actionContext);
}
}
public static class DumpingGround
{
public static Collection<MyAttribute> GetMyAttribute(HttpActionDescriptor actionDescriptor)
{
return actionDescriptor.GetCustomAttributes<MyAttribute>(true);
}
public static void DoSomething(Collection<MyAttribute> attributes)
{
Console.WriteLine("hello");
}
public static void Main()
{
var globalAction = new OnAttributeAttribute<Collection<MyAttribute>>(
new Cache<HttpActionDescriptor, Collection<MyAttribute>>(GetMyAttribute, new ActionDescriptorComparer()),
DoSomething);
//Add globalAction to global filters.
//Add MyAttribute ( or any other to an action )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment