Background
I am new to C# dotnet and I need to enable logging into my project. Therefore, I followed some online materials including Microsoft documentation. My implementation is slightly different than the example in the document as I have another constructor with dependency injection. Then I found Stackoverflow article that explains how to handle dependency injection with multiple constructors. After that, I implemented the code as below.
in Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(builder =>
{
builder.ClearProviders();
builder.AddConsole();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Then I created a sample controller and implemented the logger as below.
private ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
[HttpGet]
public IActionResult Index()
{
_logger.LogInformation("Test");
return Ok("Home controller");
}
It does work only when the
builder.ClearProviders();
builder.AddConsole();
are commented in the Program.cs
Then I implemented a logger in a class that has a constructor already with dependency injection.
private ICachingService _cashService;
private readonly ILogger<ExampleHelper> _logger;
public ExampleHelper(ICachingService cachingService)
{
_cashService = cachingService;
}
[ActivatorUtilitiesConstructor]
public ExampleHelper(ILogger<ExampleHelper> logger)
{
_logger = logger;
_logger.LogInformation("Example Logger");
}
Results are breakpoint of the _logger.LogInformation("Example Logger");
does not hit and throws the following exception.
Exception thrown: 'System.ArgumentNullException' in Microsoft.Extensions.Logging.Abstractions.dll
If further information is needed, I can provide them.
Question 1: Why Homecontroller logger is not working when clear providers and add console in program.cs ?
Question 2: How to avoid exception and print the log in the ExampleHelper class ?