Home > other >  'ServiceCollection' does not contain a definition for 'GetService'
'ServiceCollection' does not contain a definition for 'GetService'

Time:12-31

Using .net 6.0.101 in a console application Microsoft.Extensions.DependencyInjection.Abstractions gives me the error described calling the GetService method.

    var serviceProvider = new ServiceCollection();
serviceProvider
    .AddLogging()
    .AddSingleton<IParentPublisher, ParentPublisher>()
    .AddDbContext<LPContext>(options => options.UseSqlServer(configuration["connectionstring"]))
    .BuildServiceProvider();

serviceProvider
            .GetService<ILoggerFactory>()
            .AddConsole(LogLevel.Debug);

CodePudding user response:

First of all your serviceProvider should actually be named serviceCollection. Secondary - AddConsole should be called on ILoggingBuilder parameter of AddLogging (this is quite old change) and does not have overload accepting log level for latest packages.

So your code should look something like this:

var serviceCollection = new ServiceCollection();
serviceCollection
    // add stuff     
    .AddLogging(builder => builder.AddConsole());
var serviceProvider = serviceCollection.BuildServiceProvider();
var loggerFactory = serviceProvider
    .GetService<ILoggerFactory>();

You can set up console log level via appsettings:

{
    "Logging": {
        "LogLevel": {
            "Microsoft": "Warning"
        },
        "Console": {
            "LogLevel": {
                "Microsoft": "Debug"
            }
        }
    }
}
  • Related