我在Visual Studio 2019 Preview 2.2中使用默认模板创建了ASP.NET Core 3.0 Web应用程序,并尝试在启动时注入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文件下面,仅添加了日志记录。
Program.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();
}
}
}
答案 0 :(得分:10)
不幸的是,无法再将ILogger
注入ASP.NET Core 3.0中的Startup.cs中。
注意
在ASP.NET Core 3.0和更高版本中,不再可能注入 Startup.cs和Program.cs中的ILogger。看到 https://github.com/aspnet/Announcements/issues/353了解更多详情。
答案 1 :(得分:2)
这可以通过手动注册 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>));
// ...
}
答案 2 :(得分:0)
您是否已使用ServiceCollection注册记录器!应该在这里。
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();
}
答案 3 :(得分:0)
此问题与IHostBuilder
有关。
有关临时的解决方法,建议您尝试用IWebHost
代替IHostBuilder
。
像
一样更改Program.cspublic 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();
}
答案 4 :(得分:0)
如果要在调用Configure()之后记录事件,您仍然可以通过方法注入(与首选的构造方法注入相反)注入ILogger。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<TStartup> logger)
{
_logger = logger;
...
}
答案 5 :(得分:0)
从 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)
{
/// ...
}
}