Middlewares - aceryan-consulting/aceryansoft.codeflow GitHub Wiki
A common middleware need is to run code before and after the execution pipeline.
For instance let's add a middleware to catch exception globally.
var aicodeFlow = new CodeFlow();
aicodeFlow.StartNew(cfg => {
cfg.WithContext(() => new AiContext())
.UseMiddleware((ctx, next) =>
{
try
{
next();
}
catch(Exception ex)
{
//log exception and execute some logic
}
});
})
.Call((ctx, inputs) =>
{
Console.WriteLine("Hello World");
})
.Close();
aicodeFlow.Execute();
Middleware can also be define as a class implementing ICodeFlowMiddleWare
public class ExceptionHandlingMiddleware : ICodeFlowMiddleWare
{
public void Execute(ICodeFlowContext context, Action next)
{
try
{
// run code before the execution pipeline
next();
// run code after the execution pipeline
}
catch (Exception ex)
{
//log exception and execute some logic
}
}
}
The middleware class is now use as follow
var exceptionHandlingMiddleware = new ExceptionHandlingMiddleware();
var aicodeFlow = new CodeFlow();
aicodeFlow.StartNew(cfg => {
cfg.WithContext(() => new AiContext())
.UseMiddleware(exceptionHandlingMiddleware);
})
.Call((ctx, inputs) =>
{
Console.WriteLine("Hello World");
})
.Close();
aicodeFlow.Execute();
Continue reading: ActivityFilter