我正在使用.NET核心2.2构建全新的Web API.在我的配置方法中Startup.cs我已设置ILoggerFactory.当我做这样的事情并添加以下代码
loggerFactory.AddConsole();
loggerFactory.AddDebug();
Run Code Online (Sandbox Code Playgroud)
我得到的信息说这个方法已经过时了,它将在未来的版本中删除,而不是我应该使用.ILoggingBuilder没有问题,我已经用这个新的日志记录方法取代了,一旦我启动Web API我就会收到错误
InvalidOperationException:没有注册类型"Microsoft.Extensions.Logging.ILoggingBuilder"的服务.
我的输出窗口显示了这一点
无法为方法的参数'loggingBuilder'解析类型为'Microsoft.Extensions.Logging.ILoggingBuilder'的服务.
我是.NET核心的新手,但我在这里遗漏了什么?使用ILoggerFactury,我没有注册任何服务,并且日志记录可以正常工作.微软的文档在这里并没有多大帮助.
Startup.cs看起来像这样:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggingBuilder loggingBuilder)
{
loggingBuilder.AddConsole();
loggingBuilder.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler();
}
app.UseMvc();
//app.Run(async (context) =>
//{
// await context.Response.WriteAsync("Hello World!");
//});
}
}
Run Code Online (Sandbox Code Playgroud)
Program.cs看起来像这样:
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
Run Code Online (Sandbox Code Playgroud)
Joh*_*ica 19
它不起作用,因为您没有使用依赖注入容器注册日志记录组件.有两种方法可以做到这一点:
将其配置为以下内容的一部分CreateWebHostBuilder:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConsole();
logging.AddDebug();
})
.UseStartup<Startup>();
Run Code Online (Sandbox Code Playgroud)
或者,或者,在以下情况下将其注册到您的服务集合ConfigureServices:
services.AddLogging(logging =>
{
logging.AddConsole();
logging.AddDebug();
});
Run Code Online (Sandbox Code Playgroud)