Skip to content

Instantly share code, notes, and snippets.

@jermdavis
Last active May 29, 2017 13:15
Show Gist options
  • Save jermdavis/f46621f4c58b560c1089196bdc334909 to your computer and use it in GitHub Desktop.
Save jermdavis/f46621f4c58b560c1089196bdc334909 to your computer and use it in GitHub Desktop.
Pipelines with a shared logging mechanism
using System;
namespace StronglyTypedPipelines
{
public interface ILoggingPipeline
{
void RaiseMessage(IPipelineStep sender, string message, object data);
}
public abstract class LoggingPipelineStep<INPUT, OUTPUT> : IPipelineStep<INPUT, OUTPUT>
{
public ILoggingPipeline ParentPipeline { get; set; }
public abstract OUTPUT Process(INPUT input);
}
public class LoggingPipeline<INPUT, OUTPUT> : Pipeline<INPUT, OUTPUT>, ILoggingPipeline
{
public event Action<IPipelineStep, string, object> OnMessage;
void ILoggingPipeline.RaiseMessage(IPipelineStep sender, String message, object data)
{
OnMessage?.Invoke(sender, message, data);
}
}
public static class LoggingStepExtension
{
public static OUTPUT LogStep<INPUT, OUTPUT>(this INPUT input, ILoggingPipeline pipeline, LoggingPipelineStep<INPUT, OUTPUT> step)
{
step.ParentPipeline = pipeline;
return step.Process(input);
}
}
public class ExampleLoggingStep : LoggingPipelineStep<int, string>
{
public override String Process(int input)
{
ParentPipeline.RaiseMessage(this, "Calling the example step with input data", input);
var output = input.ToString();
ParentPipeline.RaiseMessage(this, "And the result is: ", output);
return output;
}
}
public class ExampleLoggingPipeline : LoggingPipeline<int,string>
{
public ExampleLoggingPipeline()
{
PipelineSteps = input => input
.LogStep(this, new ExampleLoggingStep());
}
}
public static class ExampleCode
{
public static void Run()
{
var pipeline = new ExampleLoggingPipeline();
pipeline.OnMessage += (sender, msg, data) => Console.WriteLine(String.Format("[{0}] Received: {1} {2}", sender.GetType().Name, msg, data));
var result = pipeline.Process(92);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment