Table of Contents

Class ServiceCollectionExtensions

Namespace
Codebelt.Extensions.Xunit.Hosting.AspNetCore
Assembly
Codebelt.Extensions.Xunit.Hosting.AspNetCore.dll

Extension methods for the IServiceCollection interface.

public static class ServiceCollectionExtensions
Inheritance
ServiceCollectionExtensions

Examples

The following example registers a fake IHttpContextAccessor on an IServiceCollection so that unit tests can simulate HTTP context without hosting a real server. Call AddFakeHttpContextAccessor with the desired service lifetime to control how the accessor is reused across requests.

using Codebelt.Extensions.Xunit.Hosting.AspNetCore;
using Microsoft.Extensions.DependencyInjection;

namespace WebFixtureTests;

public class ExampleFixture
{
    public IServiceCollection ConfigureServices(IServiceCollection services)
    {
        return services.AddFakeHttpContextAccessor(ServiceLifetime.Scoped);
    }
}

Methods

AddFakeHttpContextAccessor(IServiceCollection, ServiceLifetime)

Adds a unit test optimized implementation for the IHttpContextAccessor service.

public static IServiceCollection AddFakeHttpContextAccessor(this IServiceCollection services, ServiceLifetime lifetime = ServiceLifetime.Singleton)

Parameters

services IServiceCollection

The IServiceCollection to extend.

lifetime ServiceLifetime

The lifetime of the service. Default is Singleton.

Returns

IServiceCollection

A reference to services after the operation has completed.