Created
March 16, 2016 20:46
-
-
Save danielwertheim/e7dfca803b4c5ed7c71c to your computer and use it in GitHub Desktop.
Some Owin inspired message pipeline
This file contains hidden or 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading.Tasks; | |
namespace ConsoleApplication1 | |
{ | |
public class MessageEnvelope | |
{ | |
public object Message { get; } | |
public Dictionary<string, object> State { get; } | |
public MessageEnvelope(object message) | |
{ | |
Message = message; | |
State = new Dictionary<string, object>(); | |
} | |
} | |
public delegate Task Middleware(MessageEnvelope envelope); | |
public class Pipe | |
{ | |
private readonly Middleware _rootMiddleware; | |
private readonly Stack<Func<Middleware, Middleware>> _q = new Stack<Func<Middleware, Middleware>>(); | |
public Pipe(Middleware rootMiddleware) | |
{ | |
_rootMiddleware = rootMiddleware; | |
} | |
public void Use(Func<Middleware, Middleware> a) | |
{ | |
_q.Push(a); | |
} | |
public async Task Process(MessageEnvelope envelope) | |
{ | |
if (!_q.Any()) | |
return; | |
Middleware prev; | |
using (var e = _q.GetEnumerator()) | |
{ | |
if (!e.MoveNext()) | |
return; | |
prev = e.Current.Invoke(_rootMiddleware); | |
while (e.MoveNext()) | |
prev = e.Current(prev); | |
} | |
if (prev != null) | |
await prev(envelope); | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var pipe = new Pipe(e => | |
{ | |
Console.WriteLine("Root"); | |
return Task.FromResult(0); | |
}); | |
pipe.Use(next => | |
{ | |
return (async envelope => | |
{ | |
Console.WriteLine("Begin A"); | |
await next.Invoke(envelope); | |
Console.WriteLine("End A"); | |
}); | |
}); | |
pipe.Use(next => envelope => Invoke(next, envelope)); | |
pipe.Use(next => | |
{ | |
return (envelope => | |
{ | |
Console.WriteLine("STOP!"); | |
return Task.FromResult(0); | |
}); | |
}); | |
pipe.Process(new MessageEnvelope("Some message that would me an class...")).Wait(); | |
} | |
private static async Task Invoke(Middleware next, MessageEnvelope envelope) | |
{ | |
Console.WriteLine("Begin B"); | |
await next.Invoke(envelope); | |
Console.WriteLine("End B"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment