private static BodyDelegate GetResponseBodyBuilder(NancyContext result) { return (next, error, complete) => { // Wrap the completion delegate so the context is disposed on completion. // Technically we could just do this after the .Invoke below, but doing it // here gives scope for supporting async response body generation in the future. Action onComplete = () => { complete.Invoke(); result.Dispose(); }; using (var stream = new ResponseStream(next, onComplete)) { try { result.Response.Contents.Invoke(stream); } catch (Exception e) { error.Invoke(e); result.Dispose(); } } // Don't currently support cancelling, but if it gets called then dispose the context return result.Dispose; }; }