Search code examples
c#asp.net-coreloggingdependency-injectionilogger

Creating Base Controller for ASP.NET core to do logging but something is wrong with my constructor signature?


I want to have an easy way to have all the web api controllers automatically log what they are doing without explicitly tell it. Why is this incorrect ? Also, is there any better ways ?

 public class BaseController<T> : ControllerBase where T: BaseController<T>
{
    private readonly IAppLogger<T> _logger;

    public BaseController(IAppLogger<T> logger)
    {
        _logger = logger;
    }
}

 [Route("api/[controller]")]
[ApiController]
public class RfReportTypeController : BaseController<RfReportTypeController>
{
    private readonly IRfReportTypeService _rfReportTypeService;

    public RfReportTypeController(IRfReportTypeService rfReportTypeService)
    {
        _rfReportTypeService = rfReportTypeService ?? throw new ArgumentNullException(nameof(rfReportTypeService));
    }
}

Severity Code Description Project File Line Suppression State Error CS7036 There is no argument given that corresponds to the required formal parameter 'logger' of BaseController<RfReportTypeController>.BaseController(IAppLogger<RfReportTypeController>) PWDRS.WebAPI C:\Users\M3MAH02\source\repos\PWDRS\PWDRS\PWDRS.WebAPI\Controllers\RfReportTypeController.cs 17 Active


Solution

  • Need to pass parameters required by base constructor

    [Route("api/[controller]")]
    [ApiController]
    public class RfReportTypeController : BaseController<RfReportTypeController>
    {
        private readonly IRfReportTypeService _rfReportTypeService;
    
        public RfReportTypeController(
            IRfReportTypeService rfReportTypeService, 
            IAppLogger<RfReportTypeController> logger //<--NOTE THIS
        ) : base(logger) //<-- NOTE THIS
        {
            _rfReportTypeService = rfReportTypeService ?? throw new ArgumentNullException(nameof(rfReportTypeService));
        }
    }