没有注册类型'Microsoft.Extensions.Logging.ILoggingBuilder'的服务

时间:2018-12-19 04:23:37

标签: c# .net-core

我正在使用.NET core 2.2构建全新的Web API。在我的Startup.cs中,我在configure方法中设置了ILoggerFactory。当我做这样的事情并添加以下代码

loggerFactory.AddConsole();
loggerFactory.AddDebug();

我得到的信息说,此方法已过时,它将在以后的版本中删除,相反,我应该使用ILoggingBuilder。没问题,我已经用这种新的日志记录方法替换了它,并且在我启动Web API之后我收到错误

  

InvalidOperationException:没有注册类型为'Microsoft.Extensions.Logging.ILoggingBuilder'的服务。

我的输出窗口显示了

  

无法为方法的参数“ loggingBuilder”解析类型为“ Microsoft.Extensions.Logging.ILoggingBuilder”的服务。

.NET Core是我的新手,但是我在这里缺少什么吗?使用ILoggerFactury,我不必注册任何服务,日志记录就可以正常工作。 Microsoft's documentation here并没有真正的帮助。

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!");
        //});
    }
}

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>();
}

1 个答案:

答案 0 :(得分:14)

它不起作用,因为您没有在依赖项注入容器中注册日志记录组件。您可以通过两种方式执行此操作:

将其配置为ValueError: all the input array dimensions except for the concatenation axis must match exactly. 的一部分:

CreateWebHostBuilder

或者,也可以在public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureLogging((hostingContext, logging) => { logging.AddConsole(); logging.AddDebug(); }) .UseStartup<Startup>(); 下将其注册到服务集:

ConfigureServices