Last active
August 11, 2019 22:03
-
-
Save seangwright/d84ef3189d724359c291be2fa463f3b6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class PageTypeRouteAttributeCacheHelper | |
{ | |
public static readonly Dictionary<string, ControllerActionPair> ClassNameLookup; | |
static PageTypeRouteAttributeCacheHelper() | |
{ | |
var controllerTypes = typeof(PageTypeRouteAttributeCacheHelper) | |
.Assembly | |
.GetTypes() | |
.Where(t => | |
t.IsPublic && | |
t != typeof(Controller) && | |
typeof(Controller).IsAssignableFrom(t)); | |
var dictionary = new Dictionary<string, ControllerActionPair>(); | |
foreach (var controllerType in controllerTypes) | |
{ | |
var actions = controllerType | |
.GetMethods(BindingFlags.Public | BindingFlags.Instance) | |
.Where(m => m.IsDefined(typeof(PageTypeRouteAttribute))); | |
foreach (var action in actions) | |
{ | |
string[] classNames = action.GetCustomAttribute<PageTypeRouteAttribute>().ClassNames; | |
foreach (string className in classNames) | |
{ | |
if (dictionary.ContainsKey(className)) | |
{ | |
var pair = dictionary[className]; | |
throw new Exception( | |
"Duplicate Annotation: " + | |
$"{pair.ControllerName}Controller.{pair.ActionName} already registered for NodeClassName {className}. " + | |
$"Cannot be registered for {controllerType.Name}.{action.Name}" | |
); | |
} | |
dictionary.Add(className, new ControllerActionPair(controllerType.RemoveControllerSuffix(), action.Name)); | |
} | |
} | |
} | |
ClassNameLookup = dictionary; | |
} | |
private const int CONTROLLER_SUFFIX_LENGTH = 10; | |
public static string RemoveControllerSuffix(this Type controllerType) | |
{ | |
if (!typeof(Controller).IsAssignableFrom(controllerType)) | |
{ | |
throw new ArgumentException($"Type [{controllerType.Name}] is not assignable from [{nameof(Controller)}]"); | |
} | |
return controllerType | |
.Name | |
.Substring(0, controllerType.Name.Length - CONTROLLER_SUFFIX_LENGTH); | |
} | |
public readonly struct ControllerActionPair | |
{ | |
public string ControllerName { get; } | |
public string ActionName { get; } | |
public ControllerActionPair(string controllerName, string actionName) | |
{ | |
ControllerName = controllerName; | |
ActionName = actionName; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment