0

This is an example of one of my Web API controllers (for clarity, its methods are not shown):

public class TestController : ControllerBase
{
    private readonly ILogger<TestController> _logger;
    
    public TestController(ILogger<TestController> logger)
    {
        _logger = logger;
    }
}

I would like to use a custom base controller, from which other controllers will derive. This controller would provide logging object for all other controllers. Here's my new code:

public class TestController : AppControllerBase<TestController>
{
    public TestController()
    {
    }
}

public class AppControllerBase<T> : ControllerBase // compilation error here
{
    protected readonly ILogger<T> _logger;
    
    public AppControllerBase(ILogger<T> logger)
    {
        _logger = logger;
    }
}

However this results in compilation error:

CS7036
There is no argument given that corresponds to the required formal parameter 'logger' of 'AppControllerBase.AppControllerBase(ILogger)

I would expect DI to provide ILogger<TestController> in the base class constructor, but it seems not to be the case.

How could I resolve this?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Marko
  • 1,502
  • 5
  • 21
  • 40
  • Your issue is neither web api, or DI, its actually how to use constructors and base classes https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-constructors about half way down – TheGeneral Aug 25 '21 at 06:53
  • DI isn't magic - it is only calling methods and constructors that are already there. If the code doesn't compile, there is nothing for it to call. Either define the logger in all classes, and pass it down to `base`, or use property injection. – mjwills Aug 25 '21 at 06:53
  • My question has nothing to do with passing parameters to the base class, which is the subject of the linked question, but with how DI works. If it instantiates the base class with pre-built objects as enumerated in the constructor parameters, why can't it do so for a derived class? OK, I see that to do so it should have the knoledge of the generic types in the base class, information which only the derived class provides, and it makes the whole situation a little awkward, but anyway the point of the forum is to get new ideas on the things you don't know, isn't it? – Marko Aug 26 '21 at 11:47

0 Answers0