简体   繁体   中英

How to get the injected ILogger for a static class?

The following MWE works as expected but it will raise errors if I change

  • class Program to static class Program

  • GetRequiredService<ILogger<Program>>() to GetRequiredService<ILogger>()

Question

How to get the injected ILogger for a static class?

Minimal Working Example (MWE)

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;


class Application
{
    readonly ILogger logger;

    public Application(ILogger<Application> logger) => this.logger = logger;

    public void Say(string str)
    {
        Console.WriteLine(str);
        logger.LogError(str);
    }
}

class Program
{
    static void Main(string[] args)
    {
        using (var services = ConfigureServices())
        {
            services.GetRequiredService<ILogger<Program>>().LogInformation("Main");

            services.GetRequiredService<Application>().Say("Hello World");
        }
    }

    static ServiceProvider ConfigureServices()
    {
        IServiceCollection sc = new ServiceCollection()
          .AddLogging(x => x.AddConsole())
          .AddTransient<Application>();

        return sc.BuildServiceProvider();
    }
}

Unhandled Exception: System.InvalidOperationException: No service for type 'Microsoft.Extensions.Logging.ILogger' has been registered. at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Logging.Program.Main(String[] args) in F:...\\LoggingPractice\\Program.cs:line 24 Press any key to continue . . .

Why do you want to make the program class static? Typically it isn't. If you create a console app from the .net core template, it is not a static class.

To answer your first point... if you make program static... well you can't use a static class as a type argument .

To answer why you are getting the exception if you try to resolve ILogger without a type argument... You shouldn't be able to ! See the link - ILogger is always typed, it won't resolve the way you are trying to resolve it unless you specify a type (and you are not).

The exception is telling you that the ServiceProvider doesn't know how to resolve ILogger. It does however know how to resolve it if you provide a type argument eg ILogger<MyClass> .

I hope that clarifies things a bit for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM