如何在控制台应用程序中配置ConsoleLogger?

时间:2019-12-26 21:38:57

标签: c# asp.net-core .net-core

我正在尝试使用.NET CORE 3.1构建控制台应用程序,并且在注入控制台记录器时遇到问题。

在最近的版本中,似乎日志的注入方式已发生了显着变化,并且各种教学指南似乎都不符合我的尝试。

我有一个界面:

public interface IMyDoer
{
    void DoSomething();
}

还有一个我想向其中注入ILogger的类:

public class MyDoer : IMyDoer
{
    private readonly ILogger logger;
    public MyDoer(ILogger logger)
    {
        this.logger = logger;
    }

    public void DoSomething()
    {
        this.logger.Log(LogLevel.Information, "Doing something");
    } 
}

然后我有Main(),在这里我试图配置DI容器以构造Doer对象,将ILogger配置为登录到控制台。

public class Program
{
    public static void Main(string[] args)
    {
        var serviceCollection = new ServiceCollection();
        ConfigureServices(serviceCollection);

        var serviceProvider serviceCollection.BuildServiceProvider();

        var myDoer = serviceProvider.GetService<IMyDoer>();

        myDoer.DoSomething();
    }

    private static void ConfigureServices(ServiceCollection serviceCollection)
    {
        serviceCollection.AddLogging(configure => {
            configure.AddConsole();
        });

        serviceCollection.AddSingleton<IMyDoer, MyDoer>();
    }
}

作为替代,我尝试了:

public class Program
{
    static void Main(string[] args)
    {
        var serviceCollection = new ServiceCollection();
        ConfigureServices(serviceCollection);

        using (var serviceProvider = serviceCollection.BuildServiceProvider())
        using (var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()))
        {
            var myDoer = serviceProvider.GetService<IMyDoer>();

            myDoer.DoSomething();
        }
    }

    private static void ConfigureServices(ServiceCollection serviceCollection)
    {
        serviceCollection
            .AddSingleton<IMyDoer, MyDoer>();
    }
}

无论哪种情况,我都会遇到异常:

System.InvalidOperationException
  HResult=0x80131509
  Message=Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger' while attempting to activate 'MyDoer.DoSomething'.
  Source=Microsoft.Extensions.DependencyInjection

关于我应该应该如何做的任何想法?

1 个答案:

答案 0 :(得分:1)

Passed url: NAME: Site downloader - Follows an URL and downloads rendered html content. Follows and download anchor links to child pages recursively. Only follows relative links. USAGE: site-downloader [global options] command [command options] [arguments...] COMMANDS: help, h Shows a list of commands or help for one command GLOBAL OPTIONS: --url value Site url --help, -h show help (default: false) 未在ASP.NET Core DI容器中注册。而是使用package main import ( "fmt" "log" "os" "github.com/urfave/cli" ) var app = cli.NewApp() func info() { app.Name = "Site downloader" app.Usage = "Follows an URL and downloads rendered html content. Follows and download anchor links to child pages recursively. Only follows relative links." } func commands() string { var url string urlFlag := cli.StringFlag{ Name: "url", Usage: "Site url", Destination: &url, } app.Flags = []cli.Flag{ &urlFlag, } return url } func main() { info() var url = commands() fmt.Printf("Passed url: %v", url) err := app.Run(os.Args) if err != nil { log.Fatal(err) } }

ILogger

ILogger<T>使用类型名称(public class MyDoer : IMyDoer { private readonly ILogger<MyDoer> logger; public MyDoer(ILogger<MyDoer> logger) { this.logger = logger; } // ... } )作为log category

  

该类别包含在ILogger<T>实例创建的每个日志消息中。

要设置自己的日志类别并自己创建YourNamespace.MyDoer的实现,请使用ILogger

ILogger