Add helper to register IHttpContextAccessor #947

Merged
merged 1 commit into from Oct 2, 2017
Jump to file or symbol
Failed to load files and symbols.
+68 −0
Diff settings

Always

Just for now

Add helper to register IHttpContextAccessor

  • Loading branch information...
henkmollema committed Oct 2, 2017
commit 916065e0ae8e04a8f5e7631d97480a0d612a42af
@@ -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
+{
+ /// <summary>
+ /// Extension methods for configuring HttpContext services.
+ /// </summary>
+ public static class HttpServiceCollectionExtensions
+ {
+ /// <summary>
+ /// Adds a default implementation for the <see cref="IHttpContextAccessor"/> service.
+ /// </summary>
+ /// <param name="services">The <see cref="IServiceCollection"/>.</param>
+ /// <returns>The service collection.</returns>
+ public static IServiceCollection AddHttpContextAccessor(this IServiceCollection services)
+ {
+ if (services == null)
+ {
+ throw new ArgumentNullException(nameof(services));
+ }
+
+ services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
+ return services;
+ }
+ }
+}
@@ -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<ArgumentNullException>("services", () => HttpServiceCollectionExtensions.AddHttpContextAccessor(null));
+ }
+ }
+}
@@ -9,4 +9,8 @@
<ProjectReference Include="..\..\src\Microsoft.AspNetCore.Http\Microsoft.AspNetCore.Http.csproj" />
</ItemGroup>
+ <ItemGroup>
+ <PackageReference Include="Microsoft.Extensions.DependencyInjection" />
+ </ItemGroup>
+
</Project>