[英]ILogger and DependencyInjection in ASP.NET Core 2+
我注意到Startup.cs
中的ConfigureServices
中沒有明確的ILogger
注冊。
第一個問題: ILogger
如何被注入到例如控制器中。
第二個問題:如何配置ILogger
以注入中間件?
日志記錄是HostBuilder.Build過程的一部分
private void CreateServiceProvider()
{
var services = new ServiceCollection();
services.AddSingleton(_hostingEnvironment);
services.AddSingleton(_hostBuilderContext);
services.AddSingleton(_appConfiguration);
services.AddSingleton<IApplicationLifetime, ApplicationLifetime>();
services.AddSingleton<IHostLifetime, ConsoleLifetime>();
services.AddSingleton<IHost, Host>();
services.AddOptions();
services.AddLogging();//<--HERE
//...
WebHostBuilder.BuildCommonServices
private IServiceCollection BuildCommonServices(out AggregateException hostingStartupErrors)
{
//... code removed for brevity
var services = new ServiceCollection();
services.AddSingleton(_options);
services.AddSingleton<IHostingEnvironment>(_hostingEnvironment);
services.AddSingleton<Extensions.Hosting.IHostingEnvironment>(_hostingEnvironment);
services.AddSingleton(_context);
var builder = new ConfigurationBuilder()
.SetBasePath(_hostingEnvironment.ContentRootPath)
.AddConfiguration(_config);
_configureAppConfigurationBuilder?.Invoke(_context, builder);
var configuration = builder.Build();
services.AddSingleton<IConfiguration>(configuration);
_context.Configuration = configuration;
var listener = new DiagnosticListener("Microsoft.AspNetCore");
services.AddSingleton<DiagnosticListener>(listener);
services.AddSingleton<DiagnosticSource>(listener);
services.AddTransient<IApplicationBuilderFactory, ApplicationBuilderFactory>();
services.AddTransient<IHttpContextFactory, HttpContextFactory>();
services.AddScoped<IMiddlewareFactory, MiddlewareFactory>();
services.AddOptions();
services.AddLogging();
要將ILogger
注入控制器,只需將其作為依賴項包含在構造函數中
private readonly ILogger logger;
public MyController(ILogger<MyController> logger) {
this.logger = logger;
}
//...
並且框架將在激活時將其注入控制器。
與控制器一樣,Middleware vai構造函數注入也可以這樣做,
或者直接進入每個請求依賴項的Invoke
方法
public Task Invoke(HttpContext context, ILogger<MyMiddleware> logger) {
//...
}
像任何其他注入的服務
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.