Table of Contents

Class ServiceCollectionExtensions

Namespace
Trellis.Testing
Assembly
Trellis.Testing.dll

Extension methods for IServiceCollection that simplify replacing service registrations in integration tests.

public static class ServiceCollectionExtensions
Inheritance
ServiceCollectionExtensions
Inherited Members

Methods

ReplaceResourceLoader<TMessage, TResource>(IServiceCollection, Func<IServiceProvider, IResourceLoader<TMessage, TResource>>)

Replaces any existing IResourceLoader<TMessage, TResource> registration with a scoped factory, matching the production lifetime of resource loaders. For stateless fakes, capture a pre-created instance: _ => fakeLoader.

public static IServiceCollection ReplaceResourceLoader<TMessage, TResource>(this IServiceCollection services, Func<IServiceProvider, IResourceLoader<TMessage, TResource>> factory)

Parameters

services IServiceCollection

The service collection to modify.

factory Func<IServiceProvider, IResourceLoader<TMessage, TResource>>

A factory that creates a loader instance per scope.

Returns

IServiceCollection

The same IServiceCollection for chaining.

Type Parameters

TMessage

The command or query type that identifies the resource.

TResource

The resource type returned by the loader.

Examples

// Stateless fake — capture a pre-created instance
var fakeLoader = new FakeOrderResourceLoader(fakeRepo);
services.ReplaceResourceLoader<CancelOrderCommand, Order>(_ => fakeLoader);

// Scoped dependency — resolve from the container
services.ReplaceResourceLoader<CancelOrderCommand, Order>(
    sp => new FakeOrderResourceLoader(sp.GetRequiredService<AppDbContext>()));

ReplaceSingleton<TService>(IServiceCollection, TService)

Replaces all registrations of TService with a singleton instance. Common use: replacing TimeProvider with Microsoft.Extensions.Time.Testing.FakeTimeProvider in integration tests.

public static IServiceCollection ReplaceSingleton<TService>(this IServiceCollection services, TService instance) where TService : class

Parameters

services IServiceCollection

The service collection to modify.

instance TService

The singleton instance to register.

Returns

IServiceCollection

The same IServiceCollection for chaining.

Type Parameters

TService

The service type to replace.

Examples

var fakeTime = new FakeTimeProvider(DateTimeOffset.UtcNow);
services.ReplaceSingleton<TimeProvider>(fakeTime);