Repository navigation
Home
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.
- Package: Interlink
- Repository: manusoft/Interlink-cqrs-library
- License: MIT
- Features
- Packages
- Installation
- Setup
- Request / response
- Commands with no return value (Unit)
- Notifications
- Pipeline behaviors
- Pre and post processors
- Streaming requests
- Notification publish strategies
- Notification pipeline behaviors
- Request timeout
- Exceptions
- Interlink.Extensions.Logging
- Interlink.Extensions.Validation
- Interlink.AspNetCore
- ASP.NET Core controller examples
- Interlink.Analyzers
- Interlink.Extensions.Telemetry
- Notification exception strategies
- Notification exception handlers (outbox-friendly)
- API reference (overview)
- Versioning and releases
- Troubleshooting
- 🧩 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(combinesISender+IPublisher) - ⚪
Unitsupport 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) - 🧰
INotificationExceptionHandlerfor 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
| 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.
dotnet add package InterlinkOptional 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.Analyzersbuilder.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 filterusing 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);
}
}var pets = await sender.Send(new GetAllPetsQuery(), cancellationToken);If no handler is registered, Send throws HandlerNotFoundException.
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”.
// 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);
}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>.
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.
Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken);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;
}
}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-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.
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);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.
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<>));
});builder.Services.AddInterlink(options =>
{
options.DefaultRequestTimeout = TimeSpan.FromSeconds(30);
}, typeof(MyHandler).Assembly);Registers TimeoutBehavior<,> automatically. Exceeding the timeout throws TimeoutException.
Thrown when no handler can be resolved for a request type.
public class HandlerNotFoundException : InvalidOperationException
{
public Type RequestType { get; }
public Type? HandlerType { get; }
}dotnet add package Interlink.Extensions.Loggingbuilder.Services.AddInterlinkLogging();Registers LoggingBehavior<TRequest, TResponse> which logs start, success + duration, and errors.
dotnet add package Interlink.Extensions.Validationbuilder.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.
dotnet add package Interlink.AspNetCorebuilder.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).
[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()
|
Roslyn analyzer that reports ILINK001 when a type implements IRequest<TResponse> (or IRequest) but no matching IRequestHandler<,> exists in the compilation.
<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.
// 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");
}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.
<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" />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>dotnet pack src/Interlink.Analyzers -c Release -o ./nupkgsnuget.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 --clearMSBuild 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.
dotnet add package Interlink.Extensions.Telemetrybuilder.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.
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.
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.
// 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])| 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 |
- 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
- Confirm the nupkg contains:
analyzers/dotnet/cs/Interlink.Analyzers.dllbuild/Interlink.Analyzers.props
- Consumer references Interlink + Interlink.Analyzers with
IncludeAssetsincludinganalyzers. - Clear caches:
dotnet build-server shutdownanddotnet nuget locals all --clear. - Verify
obj/project.assets.jsonlists the analyzer DLL. - Prefer the props-based pack layout (see Interlink.Analyzers).
Use <Analyzer Include="..." /> or a ProjectReference with OutputItemType="Analyzer".
Use Error List filter Build Only (or rebuild and try Build + IntelliSense). Compilation-end rules are not pure IntelliSense diagnostics.
- 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).
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.