I read some asp.net core source code and get confused about injecting a Logger, let's take a middleware for example:
public class CookiePolicyMiddleware {
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public CookiePolicyMiddleware(RequestDelegate next, IOptions<CookiePolicyOptions> options, ILoggerFactory factory) {
Options = options.Value;
_next = next;
_logger = factory.CreateLogger<CookiePolicyMiddleware>();
}
// ...
}
so why not we just inject ILogger directly as:
public class CookiePolicyMiddleware {
private readonly RequestDelegate _next;
private readonly ILogger<CookiePolicyMiddleware> _logger;
public CookiePolicyMiddleware(RequestDelegate next, IOptions<CookiePolicyOptions> options, ILogger<CookiePolicyMiddleware> logger) {
Options = options.Value;
_next = next;
_logger = logger;
}
// ...
}
because the default CreateDefaultBuilder method in Program.cs will call services.AddLogging()
which will registe ILogger<>
as Logger<>
(https://source.dot.net/#Microsoft.Extensions.Logging/LoggingServiceCollectionExtensions.cs,42)
Isn't the second approach more straightforward?