Skip to content
This repository has been archived by the owner on Nov 20, 2018. It is now read-only.

Add helper to register IHttpContextAccessor #947

Merged
merged 1 commit into from Oct 2, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Add helper to register IHttpContextAccessor
  • Loading branch information
henkmollema committed Oct 2, 2017
commit 916065e0ae8e04a8f5e7631d97480a0d612a42af
31 changes: 31 additions & 0 deletions 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
{
/// <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));
}
}
}
Expand Up @@ -9,4 +9,8 @@
<ProjectReference Include="..\..\src\Microsoft.AspNetCore.Http\Microsoft.AspNetCore.Http.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
</ItemGroup>

</Project>