Skip to content
Manojbabu edited this page Nov 8, 2026 · 9 revisions

Interlink Wiki

Interlink is a lightweight mediator library for .NET. It helps you decouple application code using request/response and notification patterns, with optional pipelines, validation, logging, ASP.NET Core integration, and a Roslyn analyzer.


Table of contents

  1. Features
  2. Packages
  3. Installation
  4. Setup
  5. Request / response
  6. Commands with no return value (Unit)
  7. Notifications
  8. Pipeline behaviors
  9. Pre and post processors
  10. Streaming requests
  11. Notification publish strategies
  12. Notification pipeline behaviors
  13. Request timeout
  14. Exceptions
  15. Interlink.Extensions.Logging
  16. Interlink.Extensions.Validation
  17. Interlink.AspNetCore
  18. ASP.NET Core controller examples
  19. Interlink.Analyzers
  20. Interlink.Extensions.Telemetry
  21. Notification exception strategies
  22. Notification exception handlers (outbox-friendly)
  23. API reference (overview)
  24. Versioning and releases
  25. Troubleshooting

Features

  • 🧩 Simple mediator pattern for request/response
  • 🔁 Publish/Subscribe notification system
  • ⚡ Notification publish strategies (sequential / parallel)
  • 🔔 Notification pipeline behaviors
  • ⏱️ Optional request timeout behavior
  • 📡 Streaming requests (IStreamRequest / CreateStream)
  • 🎯 Unified IMediator (combines ISender + IPublisher)
  • ⚪ Unit support for fire-and-forget / void commands (IRequest / IRequest<Unit>)
  • 🔧 Pipeline behaviors (logging, validation, etc.)
  • 🧠 Clean separation of concerns via handlers
  • 🪝 Dependency injection support out of the box
  • 🔄 Pre and Post Processors for enhanced lifecycle control
  • 🔍 Assembly scanning for automatic handler registration
  • 🧪 Custom service factory injection
  • 🔄 Pipeline ordering via attributes or configuration
  • 🛡️ Notification exception strategies (StopOnFirst / Aggregate / Continue)
  • 🧰 INotificationExceptionHandler for per-handler failure recovery (outbox-friendly)
  • 🚨 Dedicated HandlerNotFoundException / NotificationHandlerException
  • ✅ Compatible with .NET Standard 2.0+ to .NET 10
  • 📦 Optional packages: Logging, FluentValidation, ASP.NET Core, Analyzer, Telemetry

Packages

Package Purpose
Interlink Core mediator
Interlink.Extensions.Logging Built-in logging behavior
Interlink.Extensions.Validation FluentValidation pipeline behavior
Interlink.AspNetCore Exception filter → ProblemDetails
Interlink.Analyzers Roslyn analyzer (ILINK001 missing handler)
Interlink.Extensions.Telemetry OpenTelemetry-style Activity instrumentation

Each package has its own README on NuGet. The core package ships the full usage docs.


📦 Installation

dotnet add package Interlink

Optional packages:

dotnet add package Interlink.Extensions.Logging
dotnet add package Interlink.Extensions.Validation
dotnet add package Interlink.Extensions.Telemetry
dotnet add package Interlink.AspNetCore
dotnet add package Interlink.Analyzers

Setup

builder.Services.AddInterlink();
// or scan a specific assembly:
builder.Services.AddInterlink(typeof(MyHandler).Assembly);

With options:

builder.Services.AddInterlink(options =>
{
    options.AddBehavior(typeof(MyBehavior<,>), order: 0);
    options.ServiceFactory = type => /* optional custom resolver */;
}, typeof(MyHandler).Assembly);

With extensions:

builder.Services.AddInterlink(typeof(MyHandler).Assembly);
builder.Services.AddInterlinkLogging();
builder.Services.AddInterlinkValidation(typeof(MyValidator).Assembly);
builder.Services.AddInterlinkTelemetry();    // Activity source "Interlink"
builder.Services.AddInterlinkAspNetCore();   // registers exception filter

Request / response

Define a query and handler

using Interlink;
using Interlink.Contracts;

public sealed record GetAllPetsQuery : IRequest<List<string>>;

public sealed class GetAllPetsHandler : IRequestHandler<GetAllPetsQuery, List<string>>
{
    public Task<List<string>> Handle(GetAllPetsQuery request, CancellationToken cancellationToken)
    {
        var pets = new List<string> { "Dog", "Cat", "Fish" };
        return Task.FromResult(pets);
    }
}

Send

var pets = await sender.Send(new GetAllPetsQuery(), cancellationToken);

If no handler is registered, Send throws HandlerNotFoundException.


Commands with no return value (Unit)

Interlink does not use a real C# void return on handlers (the pipeline is generic over TResponse). Instead it uses Unit — an empty struct meaning “no data”.

Types

// Command marker (same as IRequest<Unit>)
public interface IRequest : IRequest<Unit> { }

// Optional short handler interface
public interface IRequestHandler<in TRequest> : IRequestHandler<TRequest, Unit>
    where TRequest : IRequest { }

public readonly struct Unit
{
    public static readonly Unit Value = default;
    public static Task<Unit> Task => Task.FromResult(Value);
}

Example

public sealed record CreatePetCommand(string Name) : IRequest;

public sealed class CreatePetHandler : IRequestHandler<CreatePetCommand>
{
    public Task<Unit> Handle(CreatePetCommand request, CancellationToken cancellationToken)
    {
        // save...
        return Unit.Task; // or Task.FromResult(Unit.Value)
    }
}

// Caller — no response value to use
await sender.Send(new CreatePetCommand("Rex"));

Unit.Value is an empty struct. It has no payload; it only satisfies Task<TResponse>.


Notifications

public sealed class UserCreated(string userName) : INotification
{
    public string UserName { get; } = userName;
}

public sealed class SendWelcomeEmail : INotificationHandler<UserCreated>
{
    public Task Handle(UserCreated notification, CancellationToken cancellationToken)
    {
        // send email...
        return Task.CompletedTask;
    }
}

await publisher.Publish(new UserCreated("ada"));

Multiple handlers can handle the same notification type. They are invoked sequentially.


Pipeline behaviors

Signature

Task<TResponse> Handle(
    TRequest request,
    RequestHandlerDelegate<TResponse> next,
    CancellationToken cancellationToken);

Example

public sealed class TimingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : notnull
{
    public async Task<TResponse> Handle(
        TRequest request,
        RequestHandlerDelegate<TResponse> next,
        CancellationToken cancellationToken)
    {
        var sw = Stopwatch.StartNew();
        var response = await next(cancellationToken);
        sw.Stop();
        // log sw.ElapsedMilliseconds
        return response;
    }
}

Ordering

Lower order runs first (outermost).

[PipelineOrder(1)]
public sealed class FirstBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : notnull
{
    public Task<TResponse> Handle(
        TRequest request,
        RequestHandlerDelegate<TResponse> next,
        CancellationToken cancellationToken)
        => next(cancellationToken);
}

Or when registering:

options.AddBehavior(typeof(FirstBehavior<,>), order: 1);
options.AddBehavior(typeof(SecondBehavior<,>), order: 2);

Behaviors without an order are treated as int.MaxValue.


Pre and post processors

  • Pre-processors run before the pipeline.
  • Post-processors run after a successful pipeline.
public sealed class MyPre : IRequestPreProcessor<GetAllPetsQuery>
{
    public Task Process(GetAllPetsQuery request, CancellationToken cancellationToken)
        => Task.CompletedTask;
}

public sealed class MyPost : IRequestPostProcessor<GetAllPetsQuery, List<string>>
{
    public Task Process(GetAllPetsQuery request, List<string> response, CancellationToken cancellationToken)
        => Task.CompletedTask;
}

Discovered automatically by AddInterlink assembly scanning.


Streaming requests

public sealed record ExportPetsStream : IStreamRequest<PetDto>;

public sealed class ExportPetsStreamHandler : IStreamRequestHandler<ExportPetsStream, PetDto>
{
    public async IAsyncEnumerable<PetDto> Handle(
        ExportPetsStream request,
        [EnumeratorCancellation] CancellationToken cancellationToken)
    {
        await foreach (var pet in _repository.StreamAllAsync(cancellationToken))
            yield return pet;
    }
}

// Consumer
await foreach (var pet in sender.CreateStream(new ExportPetsStream(), ct))
{
    // process each item
}

// or via IMediator
await foreach (var pet in mediator.CreateStream(new ExportPetsStream(), ct))
{
    // ...
}

Register stream pipeline behaviors:

builder.Services.AddInterlink(options =>
{
    options.AddStreamBehavior(typeof(MyStreamBehavior<,>));
}, typeof(MyHandler).Assembly);

Notification publish strategies

builder.Services.AddInterlink(options =>
{
    options.PublishStrategy = PublishStrategy.Parallel; // or Sequential (default)
}, typeof(MyHandler).Assembly);
  • Sequential — handlers run one after another (ordering preserved).
  • Parallel — handlers run concurrently via Task.WhenAll.

Notification pipeline behaviors

public sealed class NotificationLoggingBehavior<TNotification> : INotificationPipelineBehavior<TNotification>
    where TNotification : INotification
{
    public async Task Handle(
        TNotification notification,
        NotificationHandlerDelegate next,
        CancellationToken cancellationToken)
    {
        // before
        await next(cancellationToken);
        // after
    }
}

builder.Services.AddInterlink(options =>
{
    options.AddNotificationBehavior(typeof(NotificationLoggingBehavior<>));
});

Request timeout

builder.Services.AddInterlink(options =>
{
    options.DefaultRequestTimeout = TimeSpan.FromSeconds(30);
}, typeof(MyHandler).Assembly);

Registers TimeoutBehavior<,> automatically. Exceeding the timeout throws TimeoutException.


Exceptions

HandlerNotFoundException

Thrown when no handler can be resolved for a request type.

public class HandlerNotFoundException : InvalidOperationException
{
    public Type RequestType { get; }
    public Type? HandlerType { get; }
}

Interlink.Extensions.Logging

dotnet add package Interlink.Extensions.Logging
builder.Services.AddInterlinkLogging();

Registers LoggingBehavior<TRequest, TResponse> which logs start, success + duration, and errors.


Interlink.Extensions.Validation

dotnet add package Interlink.Extensions.Validation
builder.Services.AddInterlinkValidation();
// or scan validators:
builder.Services.AddInterlinkValidation(typeof(CreatePetValidator).Assembly);
public sealed class CreatePetValidator : AbstractValidator<CreatePetCommand>
{
    public CreatePetValidator()
    {
        RuleFor(x => x.Name).NotEmpty().MaximumLength(100);
    }
}

On failure, throws FluentValidation.ValidationException before the handler runs.


Interlink.AspNetCore

dotnet add package Interlink.AspNetCore
builder.Services.AddControllers();
builder.Services.AddInterlinkAspNetCore();

Registers InterlinkExceptionFilter:

Exception HTTP Response
HandlerNotFoundException 404 ProblemDetails
FluentValidation.ValidationException 400 ValidationProblemDetails

FluentValidation support is detected at runtime (no hard dependency from the ASP.NET Core package).


ASP.NET Core controller examples

[ApiController]
[Route("api/[controller]")]
public class PetsController(ISender sender) : ControllerBase
{
    [HttpGet]
    public async Task<ActionResult<List<string>>> GetAll(CancellationToken ct)
    {
        var pets = await sender.Send(new GetAllPetsQuery(), ct);
        return Ok(pets);
    }

    [HttpPost]
    public async Task<IActionResult> Create([FromBody] CreatePetRequest body, CancellationToken ct)
    {
        await sender.Send(new CreatePetCommand(body.Name), ct);
        return Created();
    }

    [HttpDelete("{id:int}")]
    public async Task<IActionResult> Delete(int id, CancellationToken ct)
    {
        await sender.Send(new DeletePetCommand(id), ct);
        return NoContent();
    }
}

public sealed record CreatePetRequest(string Name);
HTTP Interlink Typical result
GET IRequest<T> Ok(result)
POST / PUT / DELETE IRequest Created() / NoContent()

Interlink.Analyzers

Roslyn analyzer that reports ILINK001 when a type implements IRequest<TResponse> (or IRequest) but no matching IRequestHandler<,> exists in the compilation.

Install on one project

<PackageReference Include="Interlink" Version="x.y.z" />
<PackageReference Include="Interlink.Analyzers" Version="x.y.z">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>

You need both packages: the analyzer resolves IRequest<> / IRequestHandler<,> from the Interlink reference. Without Interlink, the analyzer loads but emits nothing.

Example

// Warning ILINK001
public sealed record GetSomething : IRequest<string>;

// Adding this clears the warning
public sealed class GetSomethingHandler : IRequestHandler<GetSomething, string>
{
    public Task<string> Handle(GetSomething request, CancellationToken cancellationToken)
        => Task.FromResult("ok");
}

Visual Studio Error List

ILINK001 is a compilation-end diagnostic:

Filter Typical behavior
Build Only Shows after Build/Rebuild
IntelliSense Only Usually does not show
Build + IntelliSense May show after build once the analyzer is loaded correctly

dotnet build always prints the warning when it applies.

Local development reference

<ProjectReference Include="..\..\src\Interlink.Analyzers\Interlink.Analyzers.csproj"
                  OutputItemType="Analyzer"
                  ReferenceOutputAssembly="false" />

Do not use <Reference HintPath="...Analyzers.dll"> — that is not an analyzer registration.

Correct direct DLL registration:

<Analyzer Include="path\to\Interlink.Analyzers.dll" />

Package layout (maintainers)

A working analyzer package should contain at least:

analyzers/dotnet/cs/Interlink.Analyzers.dll
build/Interlink.Analyzers.props

Example props (forces the same mechanism as <Analyzer Include="...">):

<Project>
  <ItemGroup>
    <Analyzer Include="$(MSBuildThisFileDirectory)..\analyzers\dotnet\cs\Interlink.Analyzers.dll"
              Condition="Exists('$(MSBuildThisFileDirectory)..\analyzers\dotnet\cs\Interlink.Analyzers.dll')" />
  </ItemGroup>
</Project>

Testing a packed analyzer locally

dotnet pack src/Interlink.Analyzers -c Release -o ./nupkgs

nuget.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <clear />
    <add key="local" value="./nupkgs" />
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
  </packageSources>
</configuration>

Restore/build the consumer. Bump the version or clear the NuGet cache when repacking the same version:

dotnet nuget locals all --clear

Multi-project / modular monolith

MSBuild loads Directory.Build.props by walking up from each .csproj, not from the .sln path.

Recommended layout:

MySolution/
├── Directory.Build.props          ← repo root (applies to all projects below)
├── MySolution.sln
├── src/
│   ├── Modules/
│   │   ├── Catalog/
│   │   │   ├── Catalog.Application/   ← requests + handlers
│   │   │   └── ...
│   │   └── Orders/
│   └── Hosts/
│       └── MyApp.Api/
└── tests/

Root Directory.Build.props — all projects:

<Project>
  <ItemGroup Condition="'$(MSBuildProjectExtension)' == '.csproj'">
    <PackageReference Include="Interlink.Analyzers" Version="x.y.z">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>
</Project>

Opt-in per Application module:

<!-- Directory.Build.props -->
<Project>
  <PropertyGroup>
    <EnableInterlinkAnalyzers Condition="'$(EnableInterlinkAnalyzers)' == ''">false</EnableInterlinkAnalyzers>
  </PropertyGroup>
  <ItemGroup Condition="'$(EnableInterlinkAnalyzers)' == 'true'">
    <PackageReference Include="Interlink.Analyzers" Version="x.y.z">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>
</Project>
<!-- Catalog.Application.csproj -->
<PropertyGroup>
  <EnableInterlinkAnalyzers>true</EnableInterlinkAnalyzers>
</PropertyGroup>

Or enable for a whole module folder via src/Modules/Catalog/Directory.Build.props.

Project kind Analyzer useful?
Application (requests/handlers) Yes
API host (if it declares requests) Yes
Infrastructure only Optional
Tests Optional

Core Interlink package: add only where you call ISender / define handlers.


📊 Telemetry

dotnet add package Interlink.Extensions.Telemetry
builder.Services.AddInterlink(typeof(MyHandler).Assembly);
builder.Services.AddInterlinkTelemetry();

Subscribe to activity source Interlink in OpenTelemetry:

builder.Services.AddOpenTelemetry()
    .WithTracing(t => t
        .AddSource("Interlink")
        .AddAspNetCoreInstrumentation()
        .AddOtlpExporter());
Operation Activity name
Send Interlink.Send {Request}
Publish Interlink.Publish {Notification}
CreateStream Interlink.CreateStream {Request}

Failed operations set activity status to Error and add exception tags.



🛡️ Notification exception strategies

When a notification handler throws, Interlink applies a configurable policy instead of leaving failure handling entirely to outbox workarounds.

builder.Services.AddInterlink(options =>
{
    options.PublishStrategy = PublishStrategy.Parallel;
    options.NotificationExceptionStrategy = NotificationExceptionStrategy.Aggregate;
}, typeof(MyHandler).Assembly);
Strategy Behavior
StopOnFirst (default) Stop and rethrow the first handler failure
Aggregate Run all handlers; if any failed, throw AggregateException
Continue Run all handlers; failures are dispatched to exception handlers and not rethrown

Failures are wrapped in NotificationHandlerException with NotificationType and HandlerType for diagnostics.

Notification exception handlers (outbox-friendly)

public sealed class EmailFailedOutboxHandler
    : INotificationExceptionHandler<UserCreated, Exception>
{
    public Task Handle(UserCreated notification, Exception exception, CancellationToken ct)
    {
        // log, write dead-letter / outbox row, compensate...
        return Task.CompletedTask;
    }
}

Handlers are discovered by AddInterlink assembly scanning (same as notification handlers).

They run before the chosen strategy rethrows or continues, so you can persist a failure even when using StopOnFirst.


API reference (overview)

// Contracts
IRequest<TResponse>
IRequest                 // : IRequest<Unit>
INotification
Unit

// Handlers
IRequestHandler<TRequest, TResponse>
IRequestHandler<TRequest>              // : IRequestHandler<TRequest, Unit>
INotificationHandler<TNotification>

// Mediator
ISender.Send<TResponse>(IRequest<TResponse>, CancellationToken)
ISender.Send(IRequest, CancellationToken)
IPublisher.Publish<TNotification>(TNotification, CancellationToken)

// Pipeline
RequestHandlerDelegate<TResponse>
IPipelineBehavior<TRequest, TResponse>
PipelineOrderAttribute

// Processors
IRequestPreProcessor<TRequest>
IRequestPostProcessor<TRequest, TResponse>

// DI
services.AddInterlink([configure], [assemblies])

Versioning and releases

Version Status Highlights
1.0 – 1.3 ✅ Released Core mediator, notifications, pipelines, pre/post, performance
1.4 ✅ Released .NET Standard 2.0+
1.5 ✅ Released Logging, Validation, ASP.NET Core, Analyzer, exceptions, ordering fixes
1.5.1 ✅ Released Unit support for fire-and-forget / void commands (IRequest / IRequest<Unit>)
1.5.2 ✅ Released Unified IMediator (ISender + IPublisher)
1.6.0 ✅ Released Streaming, publish strategies, notification pipelines, timeout, ILINK002
1.7.0 ✅ Current Notification exception strategies, exception handlers, Telemetry package

Future ideas

  • Request exception handlers (IRequestExceptionHandler)
  • Constrained / filtered behaviors (command vs query vs stream)
  • Minimal API helpers
  • Source-generated handler registration (AOT-friendly)
  • Dynamic / externalized pipeline configuration

Troubleshooting

Analyzer works as ProjectReference but not as PackageReference

  1. Confirm the nupkg contains:
    • analyzers/dotnet/cs/Interlink.Analyzers.dll
    • build/Interlink.Analyzers.props
  2. Consumer references Interlink + Interlink.Analyzers with IncludeAssets including analyzers.
  3. Clear caches: dotnet build-server shutdown and dotnet nuget locals all --clear.
  4. Verify obj/project.assets.json lists the analyzer DLL.
  5. Prefer the props-based pack layout (see Interlink.Analyzers).

<Reference HintPath="...Analyzers.dll"> does nothing

Use <Analyzer Include="..." /> or a ProjectReference with OutputItemType="Analyzer".

Warning only in build log, not Error List

Use Error List filter Build Only (or rebuild and try Build + IntelliSense). Compilation-end rules are not pure IntelliSense diagnostics.

Handler not found at runtime

  • Handler class must be concrete and implement the correct closed generic interface.
  • Assembly must be passed to AddInterlink (or be the calling assembly when scanning defaults apply).
  • Service lifetime is scoped by default registration — ensure a scope exists (ASP.NET Core request scope is fine).

Pipeline behavior order unexpected

Set [PipelineOrder(n)] or AddBehavior(typeof(...), order: n). Lower runs first.


This wiki reflects Interlink usage patterns and packaging guidance collected for maintainers and consumers of the library.