Skip to content

Instantly share code, notes, and snippets.

@danielwertheim
Created March 16, 2016 20:46
Show Gist options
  • Save danielwertheim/e7dfca803b4c5ed7c71c to your computer and use it in GitHub Desktop.
Save danielwertheim/e7dfca803b4c5ed7c71c to your computer and use it in GitHub Desktop.
Some Owin inspired message pipeline
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