Skip to content

Integration DispatchProxy Extension

aryehcitron@gmail.com edited this page Nov 7, 2026 · 14 revisions

DispatchProxy Extension (Kronikol.Extensions.DispatchProxy)

The DispatchProxy extension provides DI helpers for replacing interface registrations with TrackingProxy<T> wrappers that record all method calls in your test diagrams.

Do you need this? Only if you have an in-process dependency accessed via an interface (e.g. a payment gateway SDK, a third-party client) and you want its method calls to appear as separate arrows in your sequence diagrams. If the dependency makes HTTP calls under the hood, TestTrackingMessageHandler already captures those. If it uses Cosmos/EF Core/Redis, the dedicated extensions already handle those. This extension is for dependencies that are completely invisible to the existing tracking — typically SDK fakes or in-process adapters where you want to show the interaction in diagrams. For a simpler, one-off alternative without this package, see RequestResponseLogger.LogPair() in Tracking Custom Dependencies.

Installation

dotnet add package Kronikol.Extensions.DispatchProxy

Client versions

The package asks for Microsoft.Extensions.DependencyInjection.Abstractions 10.0.0 or later, so a suite can pin whichever 10.x its application ships with. The package's own suite runs on the newest 10.x, and in CI on 10.0.0 as well. A project that takes it only through this package resolves 10.0.0; reference it yourself for a newer one. The floor is 10.0.0, the first release of the major, where the suite passes; before 5.27.10 it was 10.0.7, which the Kronikol core's Microsoft.AspNetCore.Mvc.Testing asked for.

From 5.27.5, ReplaceWithTracked replaces only the unkeyed registrations of the service. Before it, a keyed registration of the same type was removed with them, so replacing IFoo also dropped AddKeyedSingleton<IFoo>(...).

Quick Start

In your test's WebApplicationFactory configuration:

builder.ConfigureTestServices(services =>
{
    services.ReplaceWithTracked<IPaymentGateway>(
        new FakePaymentGateway(),
        "Payment Gateway");
});

This replaces the IPaymentGateway registration with a TrackingProxy<IPaymentGateway> that:

  1. Delegates all calls to FakePaymentGateway
  2. Logs each method invocation as a request/response pair in the test diagrams
  3. Records method arguments and return values as diagram content

API Reference

ReplaceWithTracked<TService> (simple overload)

services.ReplaceWithTracked<TService>(
    implementation,           // TService — the real/fake implementation
    serviceName,              // string — participant name in diagrams
    testInfoFetcher,          // Func<(string Name, string Id)>? — test context fetcher (optional)
    logMode,                  // TrackingLogMode — Immediate or Deferred (default: Immediate)
    httpContextAccessor,      // IHttpContextAccessor? — for dual-resolution test identity (optional, default: null)
    dependencyCategory        // string? — dependency category for participant shape/colour in diagrams (optional, default: null)
);

ReplaceWithTracked<TService> (full options overload)

services.ReplaceWithTracked<TService>(
    implementation,           // TService — the real/fake implementation
    new TrackingProxyOptions
    {
        ServiceName = "Payment Gateway",
        CallerName = "My Service",   // default: "Caller"
        ActivitySourceName = "MyApi.Pay",    // optional: creates OTel spans
        UriScheme = "mock",                  // default: "mock"
        SerializerOptions = new TrackingSerializerOptions { MaxDepth = 5 },
        LogMode = TrackingLogMode.Immediate, // or Deferred for cross-thread scenarios
        CurrentTestInfoFetcher = () => (testName, testId)
    }
);

Configuration Options

Property Type Default Description
ServiceName string (required) Target participant name in diagrams
CallerName string "Caller" Calling participant name in diagrams
ActivitySourceName string? null When set, creates an OTel Activity for each call (appears in internal flow popups). After an awaited async method, the caller's Activity.Current is what it was before the call (4.16.1; before, the proxy's span stayed current in the caller's flow and parented the caller's next call)
UriScheme string "mock" URI scheme for logged entries (e.g. mock://payment-gateway/IPaymentGateway/ChargeAsync)
SerializerOptions TrackingSerializerOptions? null Controls how arguments/return values are serialised (max depth, indentation, type filtering)
LogMode TrackingLogMode Immediate Immediate logs via RequestResponseLogger.LogPair(). Deferred queues via PendingRequestResponseLogs for cross-thread scenarios.
CurrentTestInfoFetcher Func<(string, string)>? null Provides the current test name and ID. Required for Immediate mode. For Deferred mode, the DeferredLogFlushHandler supplies test info at flush time.
DependencyCategory string? null Dependency category string for participant shape/colour in diagrams

v2.23.0+ Dual-Resolution: TrackingProxyOptions has an HttpContextAccessor property (IHttpContextAccessor?). When set, the proxy resolves test identity from HTTP request headers first, then falls back to CurrentTestInfoFetcher. The MediatR extension and the ReplaceWithTrackingProxy simplified overload (v2.26.3+) auto-resolve this from DI. See HTTP Tracking Setup › Dual-Resolution Test Identity (v2.23.0+) for details.


Log Modes

Immediate (default)

Calls RequestResponseLogger.LogPair() immediately when the proxied method is invoked. Requires CurrentTestInfoFetcher to be set (or that the proxy is called from a context where the test info is available).

Best for: Standard WebApplicationFactory tests where the proxy runs on the test thread.

Deferred

Queues the log entry via PendingRequestResponseLogs.Enqueue() without needing test context. The DeferredLogFlushHandler flushes the queue after each HTTP response, injecting the test name and ID at flush time. From 5.34.3 it flushes after a send that throws too, so the calls a server made during that send are filed under its test, where they waited for the next send that succeeded and were filed under that send's test, or never (#232).

Best for: Cross-thread scenarios where the proxied method runs on the SUT's thread (e.g. inside builder.ConfigureTestServices).


Complete Example

public class PaymentTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> _factory;

    public PaymentTests(WebApplicationFactory<Program> factory)
    {
        _factory = factory.WithWebHostBuilder(builder =>
        {
            builder.ConfigureTestServices(services =>
            {
                // Replace IPaymentGateway with a tracked fake
                services.ReplaceWithTracked<IPaymentGateway>(
                    new FakePaymentGateway(),
                    new TrackingProxyOptions
                    {
                        ServiceName = "Stripe",
                        CallerName = "Order Service",
                        ActivitySourceName = "Payments.Gateway",
                        LogMode = TrackingLogMode.Deferred // runs on SUT thread
                    });
            });
        });
    }

    [Fact]
    public async Task Placing_order_charges_payment()
    {
        var client = _factory.CreateTestTrackingClient(options);
        
        await client.PostAsJsonAsync("/api/orders", new { ProductId = "abc", Quantity = 1 });
        
        // The diagram now shows:
        // Tests → Order Service (HTTP)
        // Order Service → Stripe (IPaymentGateway/ChargeAsync)
        // Stripe → Order Service (200 OK)
        // Order Service → Tests (201 Created)
    }
}

How It Works

ReplaceWithTracked<T> does the following:

  1. Removes all existing IServiceCollection registrations for TService
  2. Creates a TrackingProxy<TService> wrapping the provided implementation
  3. Registers the proxy as a singleton

The TrackingProxy<T> uses System.Reflection.DispatchProxy under the hood:

  • Sync methods — Invoked directly; arguments serialised as request content, return value as response content
  • Task<TResult> and ValueTask<TResult> methods — Awaited; result serialised as response content
  • Task and ValueTask (void) methods — Awaited; no response content
  • Exceptions — Logged with the exception's type behind a bang (!InvalidOperationException) and its message chain in error, where it was a 500 no service sent (5.34.3, #232); the original exception is rethrown with its stack (unwrapped from TargetInvocationException; before 5.34.3 a method that threw before it returned reached the caller with a stack that began at the proxy)
  • IAsyncEnumerable<T> methods (5.34.3): answered when the enumeration ends, N items or the failure that ended it, where the call was answered 200 as soon as the stream was returned

A method that returns a ValueTask is awaited from 4.16.3. Before, it was recorded when it returned, so a call that failed later read as a success, and a ValueTask<TResult> was written by reading its result, which held the caller's thread until the call ended.

URI Format

Each logged interaction gets a URI in the format:

{scheme}://{serviceName}/{interfaceName}/{methodName}

For example: mock://stripe/IPaymentGateway/ChargeAsync

Safe Serialisation

Arguments and return values are serialised using TrackingSafeSerializer, which handles:

  • Circular references (via ReferenceHandler.IgnoreCycles)
  • CancellationToken filtering (excluded by default)
  • Mock proxy detection (Castle.Proxies namespace → <mock proxy>)
  • Task unwrapping (completed tasks → their result; pending → <pending Task>)
  • A ValueTask written as <ValueTask> and never read (from 4.16.3), since reading one can block or consume it
  • Configurable max depth (default 10)
  • Fallback to ToString() if JSON serialisation fails

When ReplaceWithTracked Won't Work

ReplaceWithTracked<T>() replaces the DI registration with a tracking proxy. This only works when the consuming code resolves the interface from DI on every call. It will silently produce no diagram entries when:

Scenario Why it fails Alternative
Framework stores a direct reference at startup The proxy is registered in DI but the framework captured the original instance before the replacement Manual decorator (see Tracking Custom Dependencies)
Singleton consumed by another singleton Constructor injection captures the original at build time Pass the tracked instance explicitly
Factory pattern bypasses IServiceProvider The interface is never resolved from DI Use the framework's own replacement API

Common interfaces affected:

  • IDistributedCache — ASP.NET caching middleware, Stratus caching
  • DbContext / IDbConnection — ORMs that cache connection references
  • Any singleton service consumed by other singletons at startup

How to Detect Silent Failure

The DiagnosticReport (enabled via DiagnosticMode = true in ReportConfigurationOptions) shows all registered tracking components and their invocation counts. A proxy with 0 invocations after a full test run indicates the proxy was bypassed:

Tracking Components
┌─────────────────────────────────────────────┬─────────────┬──────────┐
│ Component                                   │ Invocations │ Status   │
├─────────────────────────────────────────────┼─────────────┼──────────┤
│ TrackingProxy<IDistributedCache>            │ 0           │ ⚠ never  │
└─────────────────────────────────────────────┴─────────────┴──────────┘

When you see this, switch to a manual tracking decorator. See the IDistributedCache example in Tracking Custom Dependencies › Example: Tracking IDistributedCache.

Home · 🔍 Search this wiki Full-text search across every page. The “Pages” list above matches page and heading names, not page content.


Demo


Getting Started

Common Tasks

Integration Guides

Uninstrumentable / polyglot backends

Extensions

Configuration

Features

Reference

Clone this wiki locally