Last active
October 12, 2015 21:28
-
-
Save phillip-haydon/4089657 to your computer and use it in GitHub Desktop.
Custom Route Builder for Nancy
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 class NancyModule : NancyModule<RouteBuilder> | |
{ | |
} | |
public class NancyModule<T> where T : RouteBuilder | |
{ | |
private static ConcurrentDictionary<Type, Func<object>> CompiledRouteBuilders = new ConcurrentDictionary<Type, Func<object>>(); | |
public virtual T Get | |
{ | |
get | |
{ | |
return CreateRouteBuilder("GET"); | |
} | |
} | |
public virtual T Post | |
{ | |
get | |
{ | |
return CreateRouteBuilder("POST"); | |
} | |
} | |
private T CreateRouteBuilder(string verb) | |
{ | |
var currentType = typeof(T); | |
if (!CompiledRouteBuilders.ContainsKey(currentType)) | |
{ | |
var compiled = Expression.Lambda<Func<object>>(Expression.New(currentType)).Compile(); | |
CompiledRouteBuilders.TryAdd(currentType, compiled); | |
} | |
var builder = (T) CompiledRouteBuilders[currentType](); | |
builder.Verb = verb; | |
builder.Module = this as NancyModule<RouteBuilder>; | |
return builder; | |
} | |
} | |
public class RouteBuilder | |
{ | |
public virtual NancyModule<RouteBuilder> Module { get; set; } | |
public virtual string Verb { get; set; } | |
public Func<dynamic, dynamic> this[string path] | |
{ | |
set | |
{ | |
this.AddRoute(path, null, value); | |
} | |
} | |
} |
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 class MyBaseModule : NancyModule<MyRouteBuilder> | |
{ | |
public MyBaseModule() | |
{ | |
Get["/", "/{id}" = _ => | |
{ | |
... | |
} | |
} | |
public T Debug | |
{ | |
return { new MyRouteBuilder("Get"); } | |
} | |
} | |
public class MyRouteBuilder : RouteBuilder | |
{ | |
public Func<dynamic, dynamic> this[string[] paths] | |
{ | |
set | |
{ | |
// apply route implementation to all paths | |
foreach(var path in paths) | |
{ | |
this.AddRoute(path, null, value); | |
} | |
} | |
} | |
public Func<dynamic, dynamic> this[string path, string routeName] | |
{ | |
set | |
{ | |
//Add route name to header response | |
this.AddRoute(path, null, value); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment