public
Created

  • Download Gist
gistfile1.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
//BarelyMVC Fluent Router API proof of concept
 
using System;
using System.Collections.Generic;
 
namespace tester
{
class MainClass
{
public static void Main(string[] args)
{
var router=new Router();
var blog=router.Controller(() => new BlogController());
blog.Handles("/foo/bar").With((c) => c.View());
Console.WriteLine(router.Execute("/foo/bar"));
Console.ReadKey();
}
}
 
public class BlogController : HttpController
{
public string View()
{
return "meh";
}
}
 
public class HttpController
{
public string Foo{get;set;}
}
 
 
delegate T ControllerInvoker<T>();
delegate string ControllerMethod<T>(T c);
 
class Router
{
public Controller<T> Controller<T>(ControllerInvoker<T> invoker) where T:HttpController
{
var c=new Controller<T>(this, invoker);
return c;
}
public List<Route> Routes{get;private set;}
public Router()
{
Routes=new List<Route>();
}
public string Execute(string url)
{
foreach(var r in Routes)
{
if(url==r.Pattern)
{
return r.GetResponse();
}
}
throw new ApplicationException();
}
}
public class Route
{
public string Pattern{get;set;}
public ResponseController GetResponse{get;set;}
}
class Controller<T> where T:HttpController
{
ControllerInvoker<T> Invoker;
Router CurrentRouter;
public Controller(Router r, ControllerInvoker<T> invoker)
{
CurrentRouter=r;
Invoker=invoker;
}
Route CurrentRoute;
public Controller<T> Handles(string pattern)
{
CurrentRoute=new Route();
CurrentRoute.Pattern=pattern;
CurrentRouter.Routes.Add(CurrentRoute);
return this;
}
public Controller<T> With(ControllerMethod<T> method)
{
CurrentRoute.GetResponse=() => {
var c=Invoker();
c.Foo=CurrentRoute.Pattern;
return method(c);
};
return this;
}
}
public delegate string ResponseController();
 
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.