gpt4 book ai didi

c# - 无法解析类型 'Microsoft.Extensions.Logging.ILogger` 1[WebApplication1.Startup] 的服务'

转载 作者:太空狗 更新时间:2023-10-29 23:36:02 34 4
gpt4 key购买 nike

我在 Visual Studio 2019 Preview 2.2 中使用默认模板创建了一个 ASP.NET Core 3.0 Web 应用程序,并尝试在 Startup 中注入(inject)一个 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>();
});
}
}

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

最佳答案

不幸的是,无法再将 ILogger 注入(inject) ASP.NET Core 3.0 中的 Startup.cs。

https://learn.microsoft.com/en-us/azure/azure-monitor/app/ilogger#capture-ilogger-logs-from-startupcs-and-programcs-in-aspnet-core-apps

Note

In ASP.NET Core 3.0 and later, it is no longer possible to injectILogger in Startup.cs and Program.cs. Seehttps://github.com/aspnet/Announcements/issues/353 for more details.

编辑:在 Startup.cs 中的 Configure 方法中进行日志记录的一种可能方法是:

            using (var logScope = app.ApplicationServices.CreateScope())
{
var logger = logScope.ServiceProvider.GetService<ILogger<Startup>>();
logger.LogInformation("Some information");
}

关于c# - 无法解析类型 'Microsoft.Extensions.Logging.ILogger` 1[WebApplication1.Startup] 的服务',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54570904/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com