PipelineNet 0.10.1

dotnet add package PipelineNet --version 0.10.1                
NuGet\Install-Package PipelineNet -Version 0.10.1                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="PipelineNet" Version="0.10.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add PipelineNet --version 0.10.1                
#r "nuget: PipelineNet, 0.10.1"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install PipelineNet as a Cake Addin
#addin nuget:?package=PipelineNet&version=0.10.1

// Install PipelineNet as a Cake Tool
#tool nuget:?package=PipelineNet&version=0.10.1                

PipelineNet

Build status

Pipeline net is a micro framework that helps you implement the pipeline and chain of responsibility patterns. With PipelineNet you can easily separate business logic and extend your application. Pipelines can be used to execute a series of middleware sequentially without expecting a return, while chains of responsibilities do the same thing but expecting a return. And you can do it all asynchronously too.

You can obtain the package from this project through nuget:

Install-Package PipelineNet

Or if you're using dotnet CLI:

dotnet add package PipelineNet

Table of Contents generated with DocToc

Simple example

Just to check how easy it is to use PipelineNet, here is an example of exception handling using a chain of responsibility:

First we define some middleware:

public class OutOfMemoryExceptionHandler : IMiddleware<Exception, bool>
{
    public bool Run(Exception parameter, Func<Exception, bool> next)
    {
        if (parameter is OutOfMemoryException)
        {
            // Handle somehow
            return true;
        }

        return next(parameter);
    }
}

public class ArgumentExceptionHandler : IMiddleware<Exception, bool>
{
    public bool Run(Exception parameter, Func<Exception, bool> next)
    {
        if (parameter is ArgumentException)
        {
            // Handle somehow
            return true;
        }

        return next(parameter);
    }
}

Now we create a chain of responsibility with the middleware:

var exceptionHandlersChain = new ResponsibilityChain<Exception, bool>(new ActivatorMiddlewareResolver())
    .Chain<OutOfMemoryExceptionHandler>() // The order of middleware being chained matters
    .Chain<ArgumentExceptionHandler>();

Now your instance of ResponsibilityChain can be executed as many times as you want:

// The following line will execute only the OutOfMemoryExceptionHandler, which is the first middleware.
var result = exceptionHandlersChain.Execute(new OutOfMemoryException()); // Result will be true

// This one will execute the OutOfMemoryExceptionHandler first, and then the ArgumentExceptionHandler gets executed.
result = exceptionHandlersChain.Execute(new ArgumentExceptionHandler()); // Result will be true

// If no middleware matches returns a value, the default of the return type is returned, which in the case of 'bool' is false.
result = exceptionHandlersChain.Execute(new InvalidOperationException()); // Result will be false

You can even define a fallback function that will be executed after your entire chain:

var exceptionHandlersChain = new ResponsibilityChain<Exception, bool>(new ActivatorMiddlewareResolver())
    .Chain<OutOfMemoryExceptionHandler>() // The order of middleware being chained matters
    .Chain<ArgumentExceptionHandler>()
    .Finally((parameter) =>
    {
        // Do something
        return true;
    });

Now if the same line gets executed:

var result = exceptionHandlersChain.Execute(new InvalidOperationException()); // Result will be true

The result will be true because of the function defined in the Finally method.

Pipeline vs Chain of responsibility

Here is the difference between those two in PipelineNet:

  • Chain of responsibility:
    • Returns a value;
    • Have a fallback function to execute at the end of the chain;
    • Used when you want that only one middleware to get executed based on an input, like the exception handling example;
  • Pipeline:
    • Does not return a value;
    • Used when you want to execute various middleware over an input, like filterings over an image;

Middleware

In PipelineNet the middleware is a definition of a piece of code that will be executed inside a pipeline or a chain of responsibility.

We have four interfaces defining middleware:

  • The IMiddleware<TParameter> is used exclusively for pipelines, which does not have a return value.
  • The IAsyncMiddleware<TParameter> the same as above but used for asynchronous pipelines.
  • The IMiddleware<TParameter, TReturn> is used exclusively for chains of responsibility, which does have a return value.
  • The IAsyncMiddleware<TParameter, TReturn> the same as above but used for asynchronous chains of responsibility.

Besides the differences between those four kinds of middleware, they all have a similar structure, the definition of a method Run in which the first parameter is the parameter passed to the Pipeline/Chain of responsibility beind executed and the second one is an Action of Func to execute the next middleware in the flow. It is important to remember to invoke the next middleware by executing the Action/Func provided as the second parameter.

Pipelines

The pipeline can be found in two flavours: Pipeline<TParameter> and AsyncPipeline<TParameter>. Both have the same functionaly, aggregate and execute a series of middleware.

Here is an example of pipeline being configured with three middleware types:

var pipeline = new Pipeline<Bitmap>(new ActivatorMiddlewareResolver())
    .Add<RoudCornersMiddleware>()
    .Add<AddTransparencyMiddleware>()
    .Add<AddWatermarkMiddleware>();

From now on, the instance of pipeline can be used to perform the same operation over as many Bitmap instance as you like:

Bitmap image1 = (Bitmap) Image.FromFile("party-photo.png");
Bitmap image2 = (Bitmap) Image.FromFile("marriage-photo.png");
Bitmap image3 = (Bitmap) Image.FromFile("matrix-wallpaper.png");

pipeline.Execute(image1);
pipeline.Execute(image2);
pipeline.Execute(image3);

If you want to, you can use the asynchronous version, using asynchronous middleware. Changing the instantiation to:

var pipeline = new AsyncPipeline<Bitmap>(new ActivatorMiddlewareResolver())
    .Add<RoudCornersAsyncMiddleware>()
    .Add<AddTransparencyAsyncMiddleware>()
    .Add<AddWatermarkAsyncMiddleware>();

And the usage may be optimized:

Bitmap image1 = (Bitmap) Image.FromFile("party-photo.png");
Task task1 = pipeline.Execute(image1); // You can also simply use "await pipeline.Execute(image1);"

Bitmap image2 = (Bitmap) Image.FromFile("marriage-photo.png");
Task task2 = pipeline.Execute(image2);

Bitmap image3 = (Bitmap) Image.FromFile("matrix-wallpaper.png");
Task task3 = pipeline.Execute(image3);

Task.WaitAll(new Task[]{ task1, task2, task3 });

Chains of responsibility

The chain of responsibility also has two implementations: ResponsibilityChain<TParameter, TReturn> and AsyncResponsibilityChain<TParameter, TReturn>. Both have the same functionaly, aggregate and execute a series of middleware retrieving a return type.

One difference of chain responsibility when compared to pipeline is the fallback function that can be defined with the Finally method. You can set one function for chain of responsibility, calling the method more than once will replace the previous function defined.

As we already have an example of a chain of responsibility, here is an example using the asynchronous implementation: If you want to, you can use the asynchronous version, using asynchronous middleware. Changing the instantiation to:

var exceptionHandlersChain = new AsyncResponsibilityChain<Exception, bool>(new ActivatorMiddlewareResolver())
    .Chain<OutOfMemoryAsyncExceptionHandler>() // The order of middleware being chained matters
    .Chain<ArgumentAsyncExceptionHandler>()
    .Finally((ex) =>
    {
        ex.Source = ExceptionSource;
        return Task.FromResult(true);
    });

And here is the execution:

// The following line will execute only the OutOfMemoryExceptionHandler, which is the first middleware.
bool result = await exceptionHandlersChain.Execute(new OutOfMemoryException()); // Result will be true

// This one will execute the OutOfMemoryExceptionHandler first, and then the ArgumentExceptionHandler gets executed.
result = await exceptionHandlersChain.Execute(new ArgumentException()); // Result will be true

// If no middleware matches returns a value, the default of the return type is returned, which in the case of 'bool' is false.
result = await exceptionHandlersChain.Execute(new InvalidOperationException()); // Result will be false

Middleware resolver

You may be wondering what is all this ActivatorMiddlewareResolver class being passed to every instance of pipeline and chain of responsibility. This is a default implementation of the IMiddlewareResolver, which is used to create instances of the middleware types.

When configuring a pipeline/chain of responsibility you define the types of the middleware, when the flow is executed those middleware needs to be instantiated, so IMiddlewareResolver is responsible for that. Instantiated middleware are disposed automatically if they implement IDisposable or IAsyncDisposable. You can even create your own implementation, since the ActivatorMiddlewareResolver only works for parametersless constructors.

ServiceProvider implementation

An implementation of the middleware resolver for IServiceProvider was provided by @mariusz96. It is tested against Microsoft.Extensions.DependencyInjection 8.X.X, but should work with any dependency injection container that implements IServiceProvider.

You can grab it from nuget with:

Install-Package PipelineNet.ServiceProvider

Use it as follows:

services.AddScoped<IMyPipelineFactory, MyPipelineFactory>();

public interface IMyPipelineFactory
{
    IAsyncPipeline<Bitmap> CreatePipeline();
}

public class MyPipelineFactory : IMyPipelineFactory
{
    private readonly IServiceProvider _serviceProvider;

    public MyPipelineFactory(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public IAsyncPipeline<Bitmap> CreatePipeline()
    {
        return new AsyncPipeline<Bitmap>(new ActivatorUtilitiesMiddlewareResolver(_serviceProvider)) // Pass ActivatorUtilitiesMiddlewareResolver
            .Add<RoudCornersAsyncMiddleware>()
            .Add<AddTransparencyAsyncMiddleware>()
            .Add<AddWatermarkAsyncMiddleware>();
    }
}

public class RoudCornersAsyncMiddleware : IAsyncMiddleware<Bitmap>
{
    private readonly ILogger<RoudCornersAsyncMiddleware> _logger;

    // The following constructor argument will be provided by IServiceProvider
    public RoudCornersAsyncMiddleware(ILogger<RoudCornersAsyncMiddleware> logger)
    {
        _logger = logger;
    }

    public async Task Run(Bitmap parameter, Func<Bitmap, Task> next)
    {
        _logger.LogInformation("Running RoudCornersAsyncMiddleware.");
        // Handle somehow
        await next(parameter);
    }
}

Note that IServiceProvider lifetime can vary based on the lifetime of the containing class. For example, if you resolve service from a scope, and it takes an IServiceProvider, it'll be a scoped instance.

For more information on dependency injection, see: Dependency injection - .NET.

Unity implementation

An implementation of the middleware resolver for Unity was kindly provided by @ShaneYu. It is tested against Unity.Container 5.X.X, you can grab it from nuget with:

Install-Package PipelineNet.Unity

License

This project is licensed under MIT. Please, feel free to contribute with code, issues or tips 😃

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp1.0 was computed.  netcoreapp1.1 was computed.  netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard1.1 is compatible.  netstandard1.2 was computed.  netstandard1.3 was computed.  netstandard1.4 was computed.  netstandard1.5 was computed.  netstandard1.6 was computed.  netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net45 was computed.  net451 was computed.  net452 was computed.  net46 was computed.  net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen30 was computed.  tizen40 was computed.  tizen60 was computed. 
Universal Windows Platform uap was computed.  uap10.0 was computed. 
Windows Phone wpa81 was computed. 
Windows Store netcore was computed.  netcore45 was computed.  netcore451 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 1.1

  • .NETStandard 2.0

    • No dependencies.
  • .NETStandard 2.1

    • No dependencies.

NuGet packages (8)

Showing the top 5 NuGet packages that depend on PipelineNet:

Package Downloads
VirtoCommerce.ExperienceApiModule.Core

Experiene API functionality

VirtoCommerce.XDigitalCatalog

Package Description

VirtoCommerce.XPurchase

Package Description

VirtoCommerce.Xapi.Core

Experiene API functionality

Texnomic.SecureDNS.Core

Texnomic SecureDNS Core Library.

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on PipelineNet:

Repository Stars
Texnomic/SecureDNS
Secure, Modern, Fully-Featured, All-In-One Cross-Architecture & Cross-Platform DNS Server Using .NET 8.0
Version Downloads Last updated
0.10.1 1,512 7/30/2024
0.10.0 61 7/29/2024
0.10.0-alpha 83 7/13/2024
0.9.0 678,455 6/23/2019
0.9.0-beta1 1,366 5/25/2019
0.0.1 5,918 9/29/2016