Skip to content

DbConnection Interception

LAP-CHRIS\chris edited this page Mar 10, 2026 · 2 revisions

Language: English | Português (Brasil)

DbConnection Interception

The core package includes an ADO.NET interception pipeline that wraps any DbConnection so you can compose diagnostics, logging, fault injection, and related behaviors around the same connection used by your tests.

Key entry points

  • WithInterceptors(...)
  • WithInterception(...)
  • WithInterceptionFactory(...)
  • WithRegisteredInterceptors(...)
  • DbInterceptionPipeline.Wrap(...)
  • DbMockConnectionFactory.Create*WithTablesIntercepted(...)

Built-in interceptors

  • RecordingDbConnectionInterceptor
  • FaultInjectionDbConnectionInterceptor
  • LoggingDbConnectionInterceptor
  • TextWriterDbConnectionInterceptor
  • ILoggerDbConnectionInterceptor
  • DiagnosticListenerDbConnectionInterceptor
  • ActivitySourceDbConnectionInterceptor

Adoption modes

Direct wrapping

using var intercepted = connection.WithInterceptors(
    new RecordingDbConnectionInterceptor(),
    new LoggingDbConnectionInterceptor(Console.WriteLine));

Options-based composition

using var intercepted = connection.WithInterception(options =>
{
    options.UseRecording();
    options.UseLogging(Console.WriteLine);
    options.UseFaultInjection(new FaultInjectionDbConnectionInterceptor
    {
        Latency = TimeSpan.FromMilliseconds(25)
    });
});

Factory-based wrapping

var factory = new Func<DbConnection>(() => new SqliteConnectionMock(new SqliteDbMock()))
    .WithInterceptionFactory(options => options.UseRecording());

using var interceptedConnection = factory.CreateOpenConnection();

Dependency-injection path

For container-based setups, the interception story also includes helpers such as:

  • AddDbInterception(...)
  • AddDbInterceptionRecording(...)
  • AddDbInterceptionLogging(...)
  • AddDbInterceptionLogger(...)
  • AddDbInterceptionTextWriter(...)
  • AddDbInterceptionConnectionFactory(...)

Use WithRegisteredInterceptors(serviceProvider) when the interceptors are resolved from DI later in the same test or host flow.

What it is good for

  • Recording connection, command, and transaction events in tests
  • Publishing normalized logs without changing test code structure
  • Injecting deterministic latency or failures in resilience scenarios
  • Reusing the same interception pipeline through factories or DI
  • Keeping Dapper and other consumer libraries on top of a standard DbConnection

Interception and Dapper

The wrappers stay on the normal DbConnection surface, so Dapper can keep using the intercepted connection directly.

Related pages

Start in English

English

English Guided Walkthroughs

English Advanced Guides

English Providers

English Ecosystem

Português (Brasil)

Walkthroughs Guiados em Português

Guias Avançados em Português

Provedores em Português

Ecossistema em Português

Clone this wiki locally