If I create a BaseController in my Asp.Net Core 2.0 web application that capsulizes some of the common dependencies are they still necessary in the actual controllers.
F
The Microsoft.AspNetCore.MVC.Controller class comes with the extension method
HttpContext.RequestServices.GetService
Which can be used whenever the HttpContext is available in the pipeline (e.g. The HttpContext property will be Null if called from the controller's constructor)
Try this pattern
Note: make sure you include this directive using Microsoft.Extensions.DependencyInjection;
Base Controller
public abstract class BaseController : Controller where T: BaseController
{
private ILogger _logger;
protected ILogger Logger => _logger ?? (_logger = HttpContext.RequestServices.GetService>());
Child Controller
[Route("api/authors")]
public class AuthorsController : BaseController
{
public AuthorsController(IAuthorRepository authorRepository)
{
_authorRepository = authorRepository;
}
[HttpGet("LogMessage")]
public IActionResult LogMessage(string message)
{
Logger.LogInformation(message);
return Ok($"The following message has been logged: '{message}'");
}
Needless to say, remember to register your services in the Startup.cs --> ConfingureServices method