我有一个ASP.NET MVC 6(beta-4)应用程序。
public void ConfigureServices(IServiceCollection services) { // Logging services.AddLogging(); // ... } public void Configure(IApplicationBuilder app,IHostingEnvironment env,ILoggerFactory loggerfactory) { // Add the console logger. loggerfactory.AddConsole(minLevel: LogLevel.Warning); // ... }
我有一个控制器
public class HomeController : Controller { ILogger _logger; public HomeController(ILogger logger) { _logger = logger; } // ... }
但是当我没有正确地得到服务注册时:InvalidOperationException:尝试激活“HomeController”时,无法解析“Microsoft.Framework.Logging.ILogger”类型的服务。注册该记录器时我做错了什么?
解决方法
我假设services.AddLogging();正在做正确的事情并注册ILogger。在查看源(
https://github.com/aspnet/Logging/blob/d874c5726e713d3eb34938f85faf7be61aae0f2a/src/Microsoft.Framework.Logging/LoggingServiceCollectionExtensions.cs)后,我发现它实际上是注册ILogger<>。将ILogger的签名更改为ILogger< HomeController>使上述示例工作。
public class HomeController : Controller { ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } // ... }
感谢@Steve在正确的轨道上找到我。