Interlink is a lightweight and modern mediator library for .NET, designed to decouple your code through request/response and notification patterns. Built with simplicity and performance in mind, it helps streamline communication between components while maintaining a clean architecture.
- π§© 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
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.AnalyzersRegister Interlink in Program.cs (or Startup.cs):
builder.Services.AddInterlink();Scan a specific assembly:
builder.Services.AddInterlink(typeof(MyHandler).Assembly);Configure pipeline behaviors and optional custom factory:
builder.Services.AddInterlink(options =>
{
// Open-generic behaviors (order is optional; lower runs first / outermost)
options.AddBehavior(typeof(LoggingBehavior<,>), order: 0);
options.AddBehavior(typeof(ValidationBehavior<,>), order: 1);
// Optional custom resolution factory
options.ServiceFactory = type => /* your custom resolver */;
}, typeof(MyHandler).Assembly);With the extension packages:
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 class GetAllPets
{
public sealed record Query : IRequest<List<string>>;
public sealed class Handler : IRequestHandler<Query, List<string>>
{
public Task<List<string>> Handle(Query request, CancellationToken cancellationToken)
{
var pets = new List<string> { "Dog", "Cat", "Fish" };
return Task.FromResult(pets);
}
}
}using Interlink;
using Interlink.Contracts;
public class CreatePet
{
public sealed record Command(string Name) : IRequest; // or IRequest<Unit>
public sealed class Handler : IRequestHandler<Command, Unit>
{
public Task<Unit> Handle(Command request, CancellationToken cancellationToken)
{
// Save pet to database...
Console.WriteLine($"Pet '{request.Name}' created");
return Unit.Value; // or Task.FromResult(Unit.Value)
}
}
}Note
IRequestis equivalent toIRequest<Unit>.- Always return
Unit.Value(orTask.FromResult(Unit.Value)) from handlers that produce no meaningful response.
[ApiController]
[Route("api/[controller]")]
public class PetController(IMediator mediator) : ControllerBase
{
[HttpGet]
public async Task<IActionResult> GetAllPets(CancellationToken cancellationToken)
{
var pets = await mediator.Send(new GetAllPets.Query(), cancellationToken);
return Ok(pets);
}
[HttpPost]
public async Task<IActionResult> CreatePet(string name, CancellationToken cancellationToken)
{
await mediator.Send(new CreatePet.Command(name), cancellationToken);
return NoContent();
}
}You can also inject ISender if you only need request/response functionality.
If no handler is registered, Send throws HandlerNotFoundException.
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)
{
Console.WriteLine($"Welcome email sent to {notification.UserName}");
return Task.CompletedTask;
}
}
public sealed class WriteAuditLog : INotificationHandler<UserCreated>
{
public Task Handle(UserCreated notification, CancellationToken cancellationToken)
{
Console.WriteLine($"Audit: user {notification.UserName} created");
return Task.CompletedTask;
}
}public class AccountService(IMediator mediator)
{
public async Task RegisterUser(string username)
{
// Save to DB...
await mediator.Publish(new UserCreated(username));
}
}You can also inject IPublisher if you only need notification publishing.
Pipeline behaviors wrap the handler and can run logic before and after it.
public interface IPipelineBehavior<in TRequest, TResponse>
where TRequest : notnull
{
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();
Console.WriteLine($"{typeof(TRequest).Name} took {sw.ElapsedMilliseconds} ms");
return response;
}
}Use the attribute (lower value runs first / outermost):
[PipelineOrder(1)]
public sealed class FirstBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
Console.WriteLine("First behavior");
return await next(cancellationToken);
}
}
[PipelineOrder(2)]
public sealed class SecondBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
Console.WriteLine("Second behavior");
return await next(cancellationToken);
}
}Or supply the order when registering:
builder.Services.AddInterlink(options =>
{
options.AddBehavior(typeof(FirstBehavior<,>), order: 1);
options.AddBehavior(typeof(SecondBehavior<,>), order: 2);
});Pre-processors run before the pipeline.
Post-processors run after a successful pipeline.
public sealed class MyRequestPreProcessor : IRequestPreProcessor<GetAllPets.Query>
{
public Task Process(GetAllPets.Query request, CancellationToken cancellationToken)
{
Console.WriteLine("[Pre] GetAllPets");
return Task.CompletedTask;
}
}
public sealed class MyRequestPostProcessor : IRequestPostProcessor<GetAllPets.Query, List<string>>
{
public Task Process(GetAllPets.Query request, List<string> response, CancellationToken cancellationToken)
{
Console.WriteLine($"[Post] returned {response.Count} pets");
return Task.CompletedTask;
}
}They are discovered automatically by AddInterlink().
dotnet add package Interlink.Extensions.Loggingbuilder.Services.AddInterlinkLogging();This registers LoggingBehavior<TRequest, TResponse>, which logs:
- request start
- successful completion + elapsed milliseconds
- exceptions
dotnet add package Interlink.Extensions.Validation// Registers ValidationBehavior + scans for IValidator<T>
builder.Services.AddInterlinkValidation(typeof(CreateUserValidator).Assembly);Example validator:
public sealed class CreateUserValidator : AbstractValidator<CreateUser.Command>
{
public CreateUserValidator()
{
RuleFor(x => x.Email).NotEmpty().EmailAddress();
RuleFor(x => x.Name).NotEmpty().MaximumLength(100);
}
}When validation fails, a FluentValidation.ValidationException is thrown (mapped to 400 by the ASP.NET Core filter if you use it).
dotnet add package Interlink.AspNetCorebuilder.Services.AddControllers();
builder.Services.AddInterlinkAspNetCore(); // adds InterlinkExceptionFilterThe filter maps:
| Exception | HTTP Status | Response |
|---|---|---|
HandlerNotFoundException |
404 | ProblemDetails |
ValidationException* |
400 | ValidationProblemDetails |
* FluentValidation support is optional and detected at runtime (no hard dependency).
dotnet add package Interlink.Analyzers
dotnet add package Interlink| Id | Severity | Description |
|---|---|---|
| ILINK001 | Warning | Request has no matching handler |
| ILINK002 | Warning | More than one handler for the same request type |
These are compilation-end diagnostics β they show after Build / Rebuild (dotnet build or Error List Build Only).
using Interlink.Contracts;
// Warning ILINK001: No handler found for request type 'GetAllPetsQuery'
public sealed record GetAllPetsQuery : IRequest<List<string>>;Clear it by adding a handler:
using Interlink;
public sealed class GetAllPetsHandler : IRequestHandler<GetAllPetsQuery, List<string>>
{
public Task<List<string>> Handle(GetAllPetsQuery request, CancellationToken cancellationToken)
=> Task.FromResult(new List<string> { "Dog", "Cat" });
}using Interlink;
using Interlink.Contracts;
public sealed record GetSomething : IRequest;
public sealed class Handler1 : IRequestHandler<GetSomething>
{
public Task<Unit> Handle(GetSomething request, CancellationToken cancellationToken)
=> Unit.Task;
}
// Warning ILINK002 on Handler1 and Handler2:
// Multiple handlers found for request type 'GetSomething'
public sealed class Handler2 : IRequestHandler<GetSomething>
{
public Task<Unit> Handle(GetSomething request, CancellationToken cancellationToken)
=> Unit.Task;
}Keep exactly one handler per request type.
public interface IRequest<out TResponse> { }
// Non-generic form (equivalent to IRequest<Unit>)
public interface IRequest : IRequest<Unit> { }
public interface IRequestHandler<in TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken);
}
public interface INotification { }
public interface INotificationHandler<in TNotification>
where TNotification : INotification
{
Task Handle(TNotification notification, CancellationToken cancellationToken);
}/// <summary>
/// Represents a void response. Use this when a request does not return a meaningful value.
/// </summary>
public readonly struct Unit : IEquatable<Unit>
{
public static readonly Unit Value = default;
public static Task<Unit> Task => System.Threading.Tasks.Task.FromResult(Value);
...
}- Prefer
IRequest(orIRequest<Unit>) for commands that only perform an action. - Always return
Unit.Value(orTask.FromResult(Unit.Value)) from the corresponding handler.
public interface ISender
{
Task<TResponse> Send<TResponse>(IRequest<TResponse> request, CancellationToken cancellationToken = default);
Task Send(IRequest request, CancellationToken cancellationToken = default); // convenience for Unit
}
public interface IPublisher
{
Task Publish<TNotification>(TNotification notification, CancellationToken cancellationToken = default)
where TNotification : INotification;
}
/// <summary>
/// Unified mediator that combines request/response and notification publishing.
/// </summary>
public interface IMediator : ISender, IPublisher
{
}public delegate Task<TResponse> RequestHandlerDelegate<TResponse>(CancellationToken cancellationToken = default);
public interface IPipelineBehavior<in TRequest, TResponse>
where TRequest : notnull
{
Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken);
}public interface IRequestPreProcessor<in TRequest> where TRequest : notnull
{
Task Process(TRequest request, CancellationToken cancellationToken);
}
public interface IRequestPostProcessor<in TRequest, in TResponse> where TRequest : notnull
{
Task Process(TRequest request, TResponse response, CancellationToken cancellationToken);
}public class HandlerNotFoundException : InvalidOperationException
{
public Type RequestType { get; }
public Type? HandlerType { get; }
}| 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
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
}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.
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.
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.
See CHANGELOG.md for the full history. Summary:
- Notification exception strategies +
INotificationExceptionHandler+NotificationHandlerException Interlink.Extensions.Telemetrypackage
- Streaming requests, publish strategies, notification pipelines, timeout, ILINK002
- Unit/void commands,
IMediator, Logging, Validation, AspNetCore, Analyzers (ILINK001)
MIT License Β© ManuHub
