C
C#13mo ago
int

❔ How to log using hosts?

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

var builder = new HostApplicationBuilder();
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Services.AddLogging();

using var host = builder.Build();

var logger = host.Services.GetRequiredService<ILogger>();

logger.LogInformation("🙂");

await host.RunAsync();
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

var builder = new HostApplicationBuilder();
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Services.AddLogging();

using var host = builder.Build();

var logger = host.Services.GetRequiredService<ILogger>();

logger.LogInformation("🙂");

await host.RunAsync();
the error is on when I try to get the logger service: Unhandled exception. System.InvalidOperationException: No service for type 'Microsoft.Extensions.Logging.ILogger' has been registered. i thought i had already registered the logging service: builder.Services.AddLogging();
8 Replies
Pobiega
Pobiega13mo ago
iirc that logger takes a ILogger<YourClass> ie, you must resolve it as generic over the class that resolves it. in this case, Program
int
int13mo ago
var logger = host.Services.GetRequiredService<ILogger<Program>>(); works thx also, another question, what's the use of using var in this code? it works fine without using
Pobiega
Pobiega13mo ago
disposing the host when the method ends but obviously, the program ends when the method ends so not much point here
int
int13mo ago
so you suggest i remove the using?
Pobiega
Pobiega13mo ago
no
int
int13mo ago
but you said there was no point of it
Pobiega
Pobiega13mo ago
yeah, but it also doesnt do anything bad.. and it gets you in the habit of using it its only pointless in Main, since when main ends... in other methods is very much useful
Accord
Accord13mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.