无法解析类型“Microsoft.Extensions.Logging.ILogger`1[WebApplication1.Startup]”的服务
Posted
技术标签:
【中文标题】无法解析类型“Microsoft.Extensions.Logging.ILogger`1[WebApplication1.Startup]”的服务【英文标题】:Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger`1[WebApplication1.Startup]' 【发布时间】:2019-07-01 10:13:38 【问题描述】:我在 Visual Studio 2019 Preview 2.2 中使用默认模板创建了一个 ASP.NET Core 3.0 Web 应用程序,并尝试在 Startup 中注入一个 ILogger:
namespace WebApplication1
public class Startup
private readonly ILogger _logger;
public Startup(IConfiguration configuration, ILogger<Startup> logger)
Configuration = configuration;
_logger = logger;
// ...
在 Program.cs 中我还调用了 ConfigureLogging() 方法:
namespace WebApplication1
public class Program
public static void Main(string[] args)
CreateHostBuilder(args).Build().Run();
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.ClearProviders();
logging.AddConsole();
)
.ConfigureWebHostDefaults(webBuilder =>
webBuilder.UseStartup<Startup>();
);
它在 ASP.NET Core 2.x 中有效,但在 ASP.NET Core 3 中失败并出现以下错误:
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger`1[WebApplication1.Startup]' while attempting to activate 'WebApplication1.Startup'.
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
at Microsoft.AspNetCore.Hosting.Internal.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Hosting.Internal.GenericWebHostBuilder.<>c__DisplayClass13_0.<UseStartup>b__2(IApplicationBuilder app)
at Microsoft.AspNetCore.Server.IIS.Core.IISServerSetupFilter.<>c__DisplayClass2_0.<Configure>b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.Internal.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
知道是什么导致了这种行为吗?
在默认“Web 应用程序”模板的完整 Program.cs 和 Startup.cs 文件下方,仅添加了日志记录。
程序.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace WebApplication1
public class Program
public static void Main(string[] args)
CreateHostBuilder(args).Build().Run();
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.ClearProviders();
logging.AddConsole();
)
.ConfigureWebHostDefaults(webBuilder =>
webBuilder.UseStartup<Startup>();
);
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace WebApplication1
public class Startup
private readonly ILogger _logger;
public Startup(IConfiguration configuration, ILogger<Startup> logger)
Configuration = configuration;
_logger = logger;
public IConfiguration Configuration get;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
services.Configure<CookiePolicyOptions>(options =>
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
);
//services.AddTransient(typeof(ILogger<>), (typeof(Logger<>)));
services.AddMvc()
.AddNewtonsoftJson();
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting(routes =>
routes.MapApplication();
);
app.UseCookiePolicy();
app.UseAuthorization();
【问题讨论】:
我认为您应该直接使用 ILoggerFactory 而不是 ILogger? ILoggerFactory 出现相同类型的错误。 你打电话给WebHostBuilder().ConfigureLogging(...)
吗?
我没有,但我认为这对本次测试来说没问题,它应该使用默认的日志记录设置对吗?
你能分享你的Startup
或 Program.cs 吗?
【参考方案1】:
很遗憾,在 ASP.NET Core 3.0 中无法再将ILogger
注入 Startup.cs。
https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger#capture-ilogger-logs-from-startupcs-and-programcs-in-aspnet-core-apps
注意
在 ASP.NET Core 3.0 及更高版本中,不再可以注入 Startup.cs 和 Program.cs 中的 ILogger。看 https://github.com/aspnet/Announcements/issues/353了解更多详情。
编辑: 在 Startup.cs 的 Configure 方法中进行日志记录的一种可能方式是:
using (var logScope = app.ApplicationServices.CreateScope())
var logger = logScope.ServiceProvider.GetService<ILogger<Startup>>();
logger.LogInformation("Some information");
【讨论】:
那么...我们从启动时向需要 ILogger 的服务传递什么? @BrainSlugs83 我在 Configure() 方法中添加了一种方法。【参考方案2】:如果你想在调用 Configure() 之后记录事情,你仍然可以通过方法注入注入 ILogger(与首选的构造函数注入相反:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<TStartup> logger)
_logger = logger;
...
【讨论】:
【参考方案3】:这可以通过手动注册ILogger
以使用 Startup 类作为类型来解决。
例子:
public void ConfigureServices(IServiceCollection services)
// Normal AddLogging
services.AddLogging();
// Additional code to register the ILogger as a ILogger<T> where T is the Startup class
services.AddSingleton(typeof(ILogger), typeof(Logger<Startup>));
// ...
【讨论】:
只有这个解决方案适用于 .NET Core 3.1【参考方案4】:从 dotnet 3.0 开始,Web 应用程序使用 IHostBuilder 而不是 IWebHostBuilder。 所以不能再直接在 Startup 类中注入 ILogger 了。
https://github.com/dotnet/docs/issues/14900
您可以通过在构建器中直接为 Startup 类创建记录器来解决此问题。
Program.cs
public class Program
public static void Main(string[] args)
CreateHostBuilder(args)
.Build()
.Run();
public static IHostBuilder CreateHostBuilder(string[] args)
return Host.CreateDefaultBuilder(args)
.ConfigureLogging(AppLoggingConfiguration)
.ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>(); )
.UseWindowsService();
public static void AppLoggingConfiguration(ILoggingBuilder loggingBuilder)
loggingBuilder.ClearProviders();
loggingBuilder.AddDebug();
loggingBuilder.AddConsole();
loggingBuilder.AddEventLog(new EventLogSettings
SourceName = "MySourceName",
LogName = "Application",
);
Startup.cs
public class Startup
private readonly ILogger<Startup> _logger;
public Startup(IConfiguration configuration)
this.Configuration = configuration;
var lf = LoggerFactory.Create(Program.AppLoggingConfiguration);
_logger = lf.CreateLogger<Startup>();
public IConfiguration Configuration get;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
/// ...
_logger.LogInformation("Hello startup");
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
/// ...
【讨论】:
【参考方案5】:此问题与IHostBuilder
有关。
对于临时解决方法,我建议您尝试使用 IWebHost
替换 IHostBuilder
。
像改变你的 Program.cs
public class Program
public static void Main(string[] args)
BuildWebHost(args).Run();
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(logging =>
logging.ClearProviders();
logging.AddConsole();
)
.Build();
【讨论】:
虽然这确实允许应用程序启动,但您最终会遇到错误“尝试激活 '你有没有使用 ServiceCollection 来注册 Logger!它应该在这里。
serviceProvider.AddTransient(typeof(ILogger<>), (typeof(Logger<>));
或者你说,这是 Program.cs 的示例
public class Program
public static void Main(string[] args)
BuildWebHost(args).Run();
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging(logging => logging.SetMinimumLevel(LogLevel.Warning))
.UseStartup<Startup>()
.Build();
【讨论】:
感谢您的回答,但它也不起作用。以上是关于无法解析类型“Microsoft.Extensions.Logging.ILogger`1[WebApplication1.Startup]”的服务的主要内容,如果未能解决你的问题,请参考以下文章