如何在ASP.NET MVC 6中注册ILogger以进行注入 [英] How to register ILogger for injection in ASP.NET MVC 6

查看:283
本文介绍了如何在ASP.NET MVC 6中注册ILogger以进行注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC 6(beta-4)应用程序.

I have a ASP.NET MVC 6 (beta-4) app.

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

    // ...
}

我有一个控制器...

And I have a controller...

public class HomeController : 
    Controller
{
    ILogger _logger;

    public HomeController(ILogger logger) 
    {
        _logger = logger;
    }

    // ...
}

但是当我以某种方式未正确注册服务时:InvalidOperationException: Unable to resolve service for type 'Microsoft.Framework.Logging.ILogger' while attempting to activate 'HomeController'..注册记录器我在做什么错?

But when I'm not getting the service registered correctly somehow: InvalidOperationException: Unable to resolve service for type 'Microsoft.Framework.Logging.ILogger' while attempting to activate 'HomeController'.. What am I doing wrong with the registering the logger?

推荐答案

我认为services.AddLogging();做正确的事情并注册ILogger.在查看源代码之后( https://github.com/aspnet/Logging/blob/d874c5726e713d3eb34938f85faf7be61aae0f2a/src/Microsoft.Framework.Logging/LoggingServiceCollectionExtensions.cs ),我发现它实际上是在注册ILogger<>.将ILogger的签名更改为ILogger<HomeController>可使上面的示例起作用.

I assumed that services.AddLogging(); was doing the right thing and registering ILogger. After looking at the source (https://github.com/aspnet/Logging/blob/d874c5726e713d3eb34938f85faf7be61aae0f2a/src/Microsoft.Framework.Logging/LoggingServiceCollectionExtensions.cs) I found that it's actually registering ILogger<>. Changing the signature of ILogger to ILogger<HomeController> makes the above example work.

public class HomeController : 
    Controller
{
    ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger) 
    {
        _logger = logger;
    }

    // ...
}

感谢@Steve,让我走上正确的道路找到了这个.

Thanks to @Steve for setting me on the right track to find this.

这篇关于如何在ASP.NET MVC 6中注册ILogger以进行注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆