C
C#2y 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
Pobiega2y 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
intOP2y 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
Pobiega2y ago
disposing the host when the method ends but obviously, the program ends when the method ends so not much point here
int
intOP2y ago
so you suggest i remove the using?
Pobiega
Pobiega2y ago
no
int
intOP2y ago
but you said there was no point of it
Pobiega
Pobiega2y 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
Accord2y 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.
Want results from more Discord servers?
Add your server