|
2 | 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
3 | 3 |
|
4 | 4 | using System;
|
| 5 | +using System.Collections.Generic; |
5 | 6 | using System.Data.Common;
|
6 | 7 | using System.Data.SqlClient;
|
7 | 8 | using Benchmarks.Data;
|
8 | 9 | using Microsoft.AspNet.Builder;
|
9 | 10 | using Microsoft.AspNet.Hosting;
|
10 | 11 | using Microsoft.AspNet.Http;
|
| 12 | +using Microsoft.AspNet.Http.Features; |
| 13 | +using Microsoft.AspNet.Http.Internal; |
11 | 14 | using Microsoft.Data.Entity;
|
12 | 15 | using Microsoft.Extensions.Configuration;
|
13 | 16 | using Microsoft.Extensions.DependencyInjection;
|
@@ -44,6 +47,7 @@ public void ConfigureServices(IServiceCollection services)
|
44 | 47 | // No scenarios covered by the benchmarks require the HttpContextAccessor so we're replacing it with a
|
45 | 48 | // no-op version to avoid the cost.
|
46 | 49 | services.AddSingleton(typeof(IHttpContextAccessor), typeof(InertHttpContextAccessor));
|
| 50 | + services.AddSingleton(typeof(IHttpContextFactory), typeof(PooledContextFactory)); |
47 | 51 |
|
48 | 52 | if (StartupOptions.EnableDbTests)
|
49 | 53 | {
|
@@ -121,5 +125,44 @@ public class Options
|
121 | 125 |
|
122 | 126 | public string ConnectionString { get; set; }
|
123 | 127 | }
|
| 128 | + |
| 129 | + public class PooledContextFactory : IHttpContextFactory |
| 130 | + { |
| 131 | + [ThreadStatic] |
| 132 | + Queue<HttpContext> _contextPool; |
| 133 | + |
| 134 | + private Queue<HttpContext> ContextPool |
| 135 | + { |
| 136 | + get |
| 137 | + { |
| 138 | + if (_contextPool == null) |
| 139 | + { |
| 140 | + _contextPool = new Queue<HttpContext>(16); |
| 141 | + } |
| 142 | + return _contextPool; |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + public HttpContext Create(IFeatureCollection featureCollection) |
| 147 | + { |
| 148 | + if (ContextPool.Count > 0) |
| 149 | + { |
| 150 | + var context = ContextPool.Dequeue(); |
| 151 | + // Needs https://github.com/aspnet/HttpAbstractions/pull/501 |
| 152 | + // context.ReplaceFeatures(featureCollection); |
| 153 | + return context; |
| 154 | + } |
| 155 | + |
| 156 | + return new DefaultHttpContext(featureCollection); |
| 157 | + } |
| 158 | + |
| 159 | + public void Dispose(HttpContext httpContext) |
| 160 | + { |
| 161 | + if (ContextPool.Count < 16) |
| 162 | + { |
| 163 | + ContextPool.Enqueue(httpContext); |
| 164 | + } |
| 165 | + } |
| 166 | + } |
124 | 167 | }
|
125 | 168 | }
|
0 commit comments