Skip to content

Instantly share code, notes, and snippets.

@phillip-haydon
Last active October 12, 2015 21:28
Show Gist options
  • Save phillip-haydon/4089657 to your computer and use it in GitHub Desktop.
Save phillip-haydon/4089657 to your computer and use it in GitHub Desktop.
Custom Route Builder for Nancy
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);
}
}
}
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