2

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 ?

Dimuth
  • 713
  • 2
  • 11
  • 34
  • 7
    Unless you have an extremely specific reason, having those 2 constructors makes no sense. Just do `public ExampleHelper(ICachingService cachingService,ILogger logger)` and it's going to work OK. – Camilo Terevinto Sep 27 '21 at 15:15
  • Calling 2 constructors to instantiate an object is not a thing – qujck Sep 27 '21 at 15:56
  • @CamiloTerevinto Thanks for the support and I can print the log now. The only issue is when I create an object of this class, I have to pass unwanted parameter unless I use an optional parameter for the logger. – Dimuth Sep 27 '21 at 16:01
  • 1
    @DimuthLasantha The issue is that you're creating instances of that class. You are using dependency injection, you don't create instances, you request them to be injected in the constructor – Camilo Terevinto Sep 27 '21 at 16:04
  • @CamiloTerevinto Thanks for the explanation. – Dimuth Sep 27 '21 at 16:09

0 Answers0