|
3 | 3 |
|
4 | 4 | using System;
|
5 | 5 | using System.Collections.Generic;
|
6 |
| -using System.Text.Encodings.Web; |
7 | 6 | using System.Threading.Tasks;
|
8 | 7 | using Microsoft.AspNetCore.Http;
|
9 |
| -using Microsoft.AspNetCore.Routing.Internal; |
10 | 8 | using Microsoft.AspNetCore.Routing.Logging;
|
11 | 9 | using Microsoft.AspNetCore.Routing.Template;
|
12 | 10 | using Microsoft.Extensions.DependencyInjection;
|
13 | 11 | using Microsoft.Extensions.Logging;
|
14 |
| -using Microsoft.Extensions.ObjectPool; |
15 | 12 |
|
16 | 13 | namespace Microsoft.AspNetCore.Routing
|
17 | 14 | {
|
18 | 15 | public abstract class RouteBase : IRouter, INamedRouter
|
19 | 16 | {
|
| 17 | + private readonly object _loggersLock = new object(); |
| 18 | + |
20 | 19 | private TemplateMatcher _matcher;
|
21 | 20 | private TemplateBinder _binder;
|
22 | 21 | private ILogger _logger;
|
@@ -259,11 +258,25 @@ private void EnsureBinder(HttpContext context)
|
259 | 258 |
|
260 | 259 | private void EnsureLoggers(HttpContext context)
|
261 | 260 | {
|
| 261 | + // We check first using the _logger to see if the loggers have been initialized to avoid taking |
| 262 | + // the lock on the most common case. |
262 | 263 | if (_logger == null)
|
263 | 264 | {
|
264 |
| - var factory = context.RequestServices.GetRequiredService<ILoggerFactory>(); |
265 |
| - _constraintLogger = factory.CreateLogger(typeof(RouteConstraintMatcher).FullName); |
266 |
| - _logger = factory.CreateLogger(typeof(RouteBase).FullName); |
| 265 | + // We need to lock here to ensure that _constraintLogger and _logger get initialized atomically. |
| 266 | + lock (_loggersLock) |
| 267 | + { |
| 268 | + if (_logger != null) |
| 269 | + { |
| 270 | + // Multiple threads might have tried to accquire the lock at the same time. Technically |
| 271 | + // there is nothing wrong if things get reinitialized by a second thread, but its easy |
| 272 | + // to prevent by just rechecking and returning here. |
| 273 | + return; |
| 274 | + } |
| 275 | + |
| 276 | + var factory = context.RequestServices.GetRequiredService<ILoggerFactory>(); |
| 277 | + _constraintLogger = factory.CreateLogger(typeof(RouteConstraintMatcher).FullName); |
| 278 | + _logger = factory.CreateLogger(typeof(RouteBase).FullName); |
| 279 | + } |
267 | 280 | }
|
268 | 281 | }
|
269 | 282 |
|
|
0 commit comments