202

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

var services = new ServiceCollection()
    .AddLogging(logging => logging.AddConsole())
    .BuildServiceProvider();

And then I try to use it in another class like so

private readonly ILogger _logger;
    
public MyClass(ILogger logger)
{
    _logger = logger;
}

public void MyFunc()
{
    _logger.Log(LogLevel.Error, "My Message");
}

System.InvalidOperationException: 'Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger'

I've tried the solutions here but it didn't work for me.

Edit Based on Yaakov's comment below and this Github comment I'm able to resolve it correctly by doing this

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

I would have preferred to have this in the initial BuildServiceProvider but looks like I'm gonna have to repeat this every time I want to use the logger (or create my own ILogger).

9
  • So where is the part you register your servicecollection? Commented Oct 22, 2018 at 3:18
  • @EmrahSüngü I don't think I'm doing that separately. I've got other resolvers in that chain after ..AddLogging(logging => logging.AddConsole()) like .AddScoped<IMyInterface, MyMethod>() which resolves correctly.
    – reggaemahn
    Commented Oct 22, 2018 at 3:20
  • 7
    Does it work if you try resolve an ILogger<MyClass>?
    – yaakov
    Commented Oct 22, 2018 at 3:41
  • 2
    @yaakov Yes, it does actually. But is there another way to register it so that I don't have to do public MyClass(ILogger<MyClass> logger) every time?
    – reggaemahn
    Commented Oct 22, 2018 at 3:56
  • 2
    Not that I know of. I believe it's designed that way for DI to also add information about where the data was logged from.
    – yaakov
    Commented Oct 22, 2018 at 4:20

12 Answers 12

221

ILogger is no longer registered by default but ILogger<T> is. If you still want to use ILogger you can register it manually with the following (in Startup.cs):

public void ConfigureServices(IServiceCollection services)
{
    var serviceProvider = services.BuildServiceProvider();
    var logger = serviceProvider.GetService<ILogger<AnyClass>>();
    services.AddSingleton(typeof(ILogger), logger);
    ...
}

Where AnyClass can be something generic, such as:

public class ApplicationLogs
{
}

So:

public void ConfigureServices(IServiceCollection services)
{
    var serviceProvider = services.BuildServiceProvider();
    var logger = serviceProvider.GetService<ILogger<ApplicationLog>>();
    services.AddSingleton(typeof(ILogger), logger);
    ...
}

ILogger will now resolve via constructor injection.

5
  • 44
    This is considered bad practice (building your service provider from ConfigureServices). This way, all your singleton services are instantiated twice. Commented Jan 31, 2020 at 0:34
  • 11
    @MathiasLykkegaardLorenzen Including or indicating the preferred implementation would have been helpful. Commented Apr 15, 2021 at 17:52
  • Pretty sure you should register a transient that resolves ILogger<ApplicationLog> at runtime Commented Apr 22, 2021 at 5:24
  • 1
    The creation of an intermediate service provider is a bit shady, but this could be a solution to avoid it: stackoverflow.com/a/70610564/646942
    – Matze
    Commented Jan 6, 2022 at 16:45
  • 10
    To avoid double instantiation of services you can register ILogger service in next way services.AddTransient<ILogger>(s => s.GetRequiredService<ILogger<Program>>()); Commented Jul 22, 2022 at 11:51
36

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<CookiePolicyOptions>(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<MyClass> _logger;


    public MyClass(ILogger<MyClass> 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<MyClass>();//Singleton or transient?!
        var s = services.BuildServiceProvider();
        var myclass = s.GetService<MyClass>();
     }
}

enter image description here Edit: Output of the program: enter image description here

8
  • 1
    It's a console application, like the question says. What you've shown in services.AddLogging, how's that different from what I've got in the question?
    – reggaemahn
    Commented Oct 22, 2018 at 3:50
  • 1
    Let me ask again.var services = new ServiceCollection() you have created a new servicecollection right? where did you register that to your application? What does resolve the dependancy? Who creates the new instance of MyClass Commented Oct 22, 2018 at 3:55
  • Well, man since you refuse the help :) there is nothing more I can do than suggest reading upon DI Commented Oct 22, 2018 at 4:01
  • 2
    Sorry, is that how it's supposed to work or supposed to not work?
    – reggaemahn
    Commented Oct 22, 2018 at 5:05
  • This shows how it is supposed to work, as you can see in the example code that it works and logger is a ConsoleLogger. I do not understand why we can not understand each other :( Commented Oct 22, 2018 at 5:36
28

For anyone that gets this error using NLog, I found I was making the following error in my dependency injection:

        private readonly ILogger _logger;

        public ErrorController(ILogger ilogger)
        {
            _logger = ilogger;
        }

According to the documentation, in .Net 5, you need to add a type of the Controller itself to the logger in order to avoid this issue. Dependency injecting as such fixed the error:

        private readonly ILogger<ErrorController> _logger;

        public ErrorController(ILogger<ErrorController> ilogger)
        {
            _logger = ilogger;
        }

After making the above change, this fixed my issue. DO NOT ATTEMPT ANY OF THE SOLUTIONS HERE! This will only send you down a rabbit hole.

Hope this helps anyone in the future!

25

For .NET Core 3.1, be sure to include the

Microsoft.Extensions.Logging

package and configure logging by calling

IServiceCollection services = new ServiceCollection();
services.AddLogging();
2
  • 7
    THIS is the real answer I was looking for... <3 Working on custom ServiceProvider on WPF Core like a charm.
    – Nk54
    Commented Oct 23, 2021 at 19:31
  • 5
    This doesn't work in .Net 6.0 Commented Mar 29, 2023 at 1:45
20

In .NET Core, ILogger<T> is automatically registered for you. As ILogger<T> inherits from ILogger, you can request an instance of ILogger<T> from the IServiceProvider.

For example: services.AddSingleton<ILogger>(svc => svc.GetRequiredService<ILogger<MyClassType>>());

Note that this will return an ILogger<MyClassType> wherever you've got a non-generic ILogger constructor parameter so if you need more than one, look into creating it specifically for that instance by using the AddSingleton (or transient/or scoped) implementationFactory override.

0
17

As noted in a comment, the accepted answer has the problem that BuildServiceProvider should not be used in ConfigureServices, since it creates another copy of each singleton (in fact, of the whole DI container). Here is an alternative one-liner that avoids that problem. In ConfigureServices, add the line

services.AddSingleton<Microsoft.Extensions.Logging.ILogger>(provider => 
   provider.GetRequiredService<Microsoft.Extensions.Logging.ILogger<AnyClass>>());

where AnyClass can be any class, as explained in the accepted answer. This redirects the resolution of ILogger to that of ILogger<AnyClass>.

Like the accepted answer, this one has the disadvantage that Serilog's SourceContext will be set to AnyClass. So, if your Serilog configuration contains an outputTemplate that contains {SourceContext}, your log will show AnyClass instead of the class that contains the logging statement.

2
  • 1
    This is a great approach. Sleek and clean. Commented Jul 5, 2021 at 5:29
  • This worked for me in a rather unique worst case scenario (winforms with a host builder)
    – m12lrpv
    Commented Jan 23 at 23:26
8

The accepted answer (as provided by @sam-shiles) goes in the right direction. I don't like that it requires building an intermediate service provider, and the registration of a singleton instance is maybe not wanted as well.

So, I suggest the registration of a factory instead, that utilizes ILoggerFactory. The creation of an empty class (like AnyClass is also not needed).

...
services.AddTransient(provider =>
{
    var loggerFactory = provider.GetRequiredService<ILoggerFactory>();
    const string categoryName = "Any";
    return loggerFactory.CreateLogger(categoryName);
});
...
6

This answer isn't necessarily for .net Core or whatever dependency injection is being used by the poster. I ran across this searching for a way to fix this error using Autofac in an asp.net forms web application. The answer of logging not being "registered by default" led me to add this to my registrations:

builder.RegisterType<LoggerFactory>().As<ILoggerFactory>().SingleInstance();
builder.RegisterGeneric(typeof(Logger<>)).As(typeof(ILogger<>)).SingleInstance();

And now it works for me. This is the second time I searched for this answer and ended up here, I forgot how I fixed it the first time. So I thought I'd post my answer.

1
5

Based on @Barry answer above found out how to register generic log provider for Microsoft.Extensions.DependencyInjection:

var services = new ServiceCollection()
                            .AddLogging(logging => logging.AddConsole())
                            .BuildServiceProvider();

services.AddSingleton<ILoggerFactory, LoggerFactory>()
services.Add(ServiceDescriptor.Describe(typeof(ILogger<>),typeof(Logger<>),ServiceLifetime.Scoped))
4

The approach I used when trying to use an ILogger (Because it's no longer injected), as to inject a ILoggerFactory, and then when your code wants a specific logger (say its some custom factory you're newing up, LoggerFactory.CreateLogger("Logger Name") - Below

But for your case,it looks like you want a ILogger<MyClass>

public class MyClass
{

    private readonly ILoggerFactory _loggerFactory;


    public MyClass(ILoggerFactory loggerFactory)
    {
        _loggerFactory = _loggerFactory;
    }
    public void MyFunc()
    {
       new MyNewThatsASpecialCase(_loggerFactory.CreateLogger("MyNewThatsASpecialCase"));
    }
}
3
  • This worked for me as LoggerFactory was the only instance available at the time I was requesting the service and not the class loggers.
    – mattygee
    Commented Aug 3, 2021 at 16:56
  • This syntax is a bit more refactoring-friendly LoggerFactory.CreateLogger<MyClass>();
    – Brad Irby
    Commented Sep 23, 2022 at 8:28
  • I did say in my answer, there are two options Logger<T> or "MySpecialCaseLogger" Commented Sep 26, 2022 at 14:23
4

This is what worked for me to get DI working for ILogger.

For .NET Core see: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-5.0

Specifically:

.ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.AddConsole();
            })

Reference:

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
    .ConfigureLogging(logging =>
    {
        logging.ClearProviders();
        logging.AddConsole();
    })
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.UseStartup<Startup>();
    });
1
0

Maybe someone else is stumbling over this cause: we had erroneously updated the package Microsoft.Extensions.DependencyInjection.Abstractions to version 8.0.0 whereas the function app is still running on .NET 6 at the moment. After downgrading the dependency to 6.0.4 everything started working as expected again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.