@@ -80,7 +80,13 @@ public static IHostBuilder UseSerilog(
80
80
collection . AddSingleton < ILoggerFactory > ( services => new SerilogLoggerFactory ( logger , dispose ) ) ;
81
81
}
82
82
83
- ConfigureServices ( collection , logger ) ;
83
+ if ( logger != null )
84
+ {
85
+ // This won't (and shouldn't) take ownership of the logger.
86
+ collection . AddSingleton ( logger ) ;
87
+ }
88
+ bool useRegisteredLogger = logger != null ;
89
+ ConfigureDiagnosticContext ( collection , useRegisteredLogger ) ;
84
90
} ) ;
85
91
86
92
return builder ;
@@ -221,32 +227,26 @@ public static IHostBuilder UseSerilog(
221
227
222
228
return factory ;
223
229
} ) ;
224
-
225
- // Null is passed here because we've already (lazily) registered `ILogger`
226
- ConfigureServices ( collection , null ) ;
230
+
231
+ ConfigureDiagnosticContext ( collection , preserveStaticLogger ) ;
227
232
} ) ;
228
233
229
234
return builder ;
230
235
}
231
236
232
- static void ConfigureServices ( IServiceCollection collection , ILogger logger )
237
+ static void ConfigureDiagnosticContext ( IServiceCollection collection , bool useRegisteredLogger )
233
238
{
234
239
if ( collection == null ) throw new ArgumentNullException ( nameof ( collection ) ) ;
235
240
236
- if ( logger != null )
237
- {
238
- // This won't (and shouldn't) take ownership of the logger.
239
- collection . AddSingleton ( logger ) ;
240
- }
241
-
242
- // Registered to provide two services...
243
- var diagnosticContext = new DiagnosticContext ( logger ) ;
244
-
241
+ // Registered to provide two services...
245
242
// Consumed by e.g. middleware
246
- collection . AddSingleton ( diagnosticContext ) ;
247
-
243
+ collection . AddSingleton ( services =>
244
+ {
245
+ ILogger logger = useRegisteredLogger ? services . GetRequiredService < RegisteredLogger > ( ) . Logger : null ;
246
+ return new DiagnosticContext ( logger ) ;
247
+ } ) ;
248
248
// Consumed by user code
249
- collection . AddSingleton < IDiagnosticContext > ( diagnosticContext ) ;
249
+ collection . AddSingleton < IDiagnosticContext > ( services => services . GetRequiredService < DiagnosticContext > ( ) ) ;
250
250
}
251
251
}
252
252
}
0 commit comments