diff --git a/src/Microsoft.AspNetCore.Http/HttpServiceCollectionExtensions.cs b/src/Microsoft.AspNetCore.Http/HttpServiceCollectionExtensions.cs new file mode 100644 index 0000000000..cccfe6d4e6 --- /dev/null +++ b/src/Microsoft.AspNetCore.Http/HttpServiceCollectionExtensions.cs @@ -0,0 +1,31 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace Microsoft.Extensions.DependencyInjection +{ + /// + /// Extension methods for configuring HttpContext services. + /// + public static class HttpServiceCollectionExtensions + { + /// + /// Adds a default implementation for the service. + /// + /// The . + /// The service collection. + public static IServiceCollection AddHttpContextAccessor(this IServiceCollection services) + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + services.TryAddSingleton(); + return services; + } + } +} diff --git a/test/Microsoft.AspNetCore.Http.Tests/HttpServiceCollectionExtensionsTests.cs b/test/Microsoft.AspNetCore.Http.Tests/HttpServiceCollectionExtensionsTests.cs new file mode 100644 index 0000000000..a317e99346 --- /dev/null +++ b/test/Microsoft.AspNetCore.Http.Tests/HttpServiceCollectionExtensionsTests.cs @@ -0,0 +1,33 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace Microsoft.AspNetCore.Http.Tests +{ + public class HttpServiceCollectionExtensionsTests + { + [Fact] + public void AddHttpContextAccessor_AddsWithCorrectLifetime() + { + // Arrange + var services = new ServiceCollection(); + + // Act + services.AddHttpContextAccessor(); + + // Assert + var descriptor = services[0]; + Assert.Equal(ServiceLifetime.Singleton, descriptor.Lifetime); + Assert.Equal(typeof(HttpContextAccessor), descriptor.ImplementationType); + } + + [Fact] + public void AddHttpContextAccessor_ThrowsWithoutServices() + { + Assert.Throws("services", () => HttpServiceCollectionExtensions.AddHttpContextAccessor(null)); + } + } +} diff --git a/test/Microsoft.AspNetCore.Http.Tests/Microsoft.AspNetCore.Http.Tests.csproj b/test/Microsoft.AspNetCore.Http.Tests/Microsoft.AspNetCore.Http.Tests.csproj index e47d0f44fb..8e5a9fd0ba 100644 --- a/test/Microsoft.AspNetCore.Http.Tests/Microsoft.AspNetCore.Http.Tests.csproj +++ b/test/Microsoft.AspNetCore.Http.Tests/Microsoft.AspNetCore.Http.Tests.csproj @@ -9,4 +9,8 @@ + + + +