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

Commit 681533e

Browse files
committed
Set IHttpContextAccessor only if DI provides it
1 parent 4efc40d commit 681533e

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

src/Microsoft.AspNet.Http/HttpContextFactory.cs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@ public class HttpContextFactory : IHttpContextFactory
99
{
1010
private IHttpContextAccessor _httpContextAccessor;
1111

12+
public HttpContextFactory() : this(httpContextAccessor: null)
13+
{
14+
}
15+
1216
public HttpContextFactory(IHttpContextAccessor httpContextAccessor)
1317
{
1418
_httpContextAccessor = httpContextAccessor;
@@ -17,13 +21,19 @@ public HttpContextFactory(IHttpContextAccessor httpContextAccessor)
1721
public HttpContext Create(IFeatureCollection featureCollection)
1822
{
1923
var httpContext = new DefaultHttpContext(featureCollection);
20-
_httpContextAccessor.HttpContext = httpContext;
24+
if (_httpContextAccessor != null)
25+
{
26+
_httpContextAccessor.HttpContext = httpContext;
27+
}
2128
return httpContext;
2229
}
2330

2431
public void Dispose(HttpContext httpContext)
2532
{
26-
_httpContextAccessor.HttpContext = null;
33+
if (_httpContextAccessor != null)
34+
{
35+
_httpContextAccessor.HttpContext = null;
36+
}
2737
}
2838
}
2939
}

test/Microsoft.AspNet.Http.Tests/HttpContextFactoryTests.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,16 @@ public void CreateHttpContextSetsHttpContextAccessor()
2121
// Assert
2222
Assert.True(ReferenceEquals(context, accessor.HttpContext));
2323
}
24+
25+
[Fact]
26+
public void AllowsCreatingContextWithoutSettingAccessor()
27+
{
28+
// Arrange
29+
var contextFactory = new HttpContextFactory();
30+
31+
// Act & Assert
32+
var context = contextFactory.Create(new FeatureCollection());
33+
contextFactory.Dispose(context);
34+
}
2435
}
2536
}

0 commit comments

Comments
 (0)