Unable to resolve ILogger from Microsoft.Extensions.Logging

前端 未结 7 1042
太阳男子
太阳男子 2021-02-02 04:56

I\'ve configured my console application\'s Main like so

var services = new ServiceCollection()
                .AddLogging(logging => logging.Add         


        
7条回答
  •  时光说笑
    2021-02-02 05:31

    I am assuming you are using the default template for .net core web application.
    In your your Startup.cs you should have a method like this↓↓↓↓↓↓↓

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure(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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //Do the service register here and extra stuff you want
             services.AddLogging(config =>
            {
                config.AddDebug();
                config.AddConsole();
                //etc
            });
    
        }
    

    Edit: I have written a simple program for you to show how it works

    public class MyClass
    {
    
        private readonly ILogger _logger;
    
    
        public MyClass(ILogger logger)
        {
            _logger = logger;
        }
        public void MyFunc()
        {
            _logger.Log(LogLevel.Error, "My Message");
        }
    }
    
    
    
    public class Program
    {
        public static void Main(string[] args)
        {
            var services = new ServiceCollection().AddLogging(logging => logging.AddConsole());
            services.AddSingleton();//Singleton or transient?!
            var s = services.BuildServiceProvider();
            var myclass = s.GetService();
         }
    }
    

    Edit: Output of the program:

提交回复
热议问题