LoggerFactory Generates InvalidOperationException
Asked Answered
H

2

23

I've created a console application using Microsoft.Extensions.Logging that uses a service layer.

Program.cs

public static void Main(string[] args)
{
    // Create service collection
    var serviceCollection = new ServiceCollection();
    ConfigureServices(serviceCollection);

    // Create service provider
    var serviceProvider = serviceCollection.BuildServiceProvider();

    // Entry to run app
    serviceProvider.GetService<App>().Run().RunSynchronously();
}

private static void ConfigureServices(IServiceCollection serviceCollection)
{
    // Configuration
    var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", false)
        .Build();

    serviceCollection.AddOptions();
    serviceCollection.Configure<Settings>(options =>
    {
        //...
    });

    // Services
    serviceCollection.AddTransient<IOneService, OneService>();
    serviceCollection.AddTransient<ISecondService, SecondService>();

    // Repositories
    serviceCollection.AddTransient<MyContext, MyContext>();
    serviceCollection.AddTransient<IOneRepository, OneRepository>();

    // App
    serviceCollection.AddTransient<App>();

    // Logger

    // Automapper
    serviceCollection.AddSingleton(new AutoMapperProfileConfiguration());
    serviceCollection.AddScoped<IMapper>(sp =>
        new Mapper(sp.GetRequiredService<IConfigurationProvider>(), sp.GetService));
}

I'm getting this error

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

and I'm guessing that i have to setup LoggerFactory and Microsoft.Extensions.Logging for .NET Core Logging, but I can't get it right.

I've tried something like this in Main():

// Attempt 1
ILoggerFactory loggerFactory = new LoggerFactory()
    .AddConsole()
    .AddDebug();
ILogger logger = loggerFactory.CreateLogger<Program>();
logger.LogInformation(
  "This is a test of the emergency broadcast system.");
  
// Attempt 2
serviceCollection.AddSingleton(new LoggerFactory()
    .AddConsole()
    .AddDebug());
    

Any ideas?

Hudspeth answered 19/9, 2017 at 8:11 Comment(1)
You forgot to call .AddLogging() on the service collection to add that functionality to the container.Mirza
G
28

It should work:

var serviceProvider = new ServiceCollection()
                      .AddLogging() //<-- You were missing this
                      .BuildServiceProvider();
//get logger
var logger = serviceProvider.GetService<ILoggerFactory>()
            .CreateLogger<Program>();

Packages to install : Microsoft.Extensions.DependencyInjection; Microsoft.Extensions.Logging;

Gone answered 19/9, 2017 at 9:36 Comment(0)
S
3

For netCore

var serviceProvider = new ServiceCollection()
    .AddLogging(x => x.AddConsole().SetMinimumLevel(LogLevel.Debug))
    .BuildServiceProvider();

var logger = serviceProvider.GetService<ILoggerFactory>()
    .CreateLogger<Program>();

logger.LogDebug("Starting Program...");
Shad answered 20/12, 2021 at 10:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.