Dependency injection duplication in Controller and BaseController in .Net Core 2.0

前端 未结 3 942
太阳男子
太阳男子 2021-02-01 21:54

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

3条回答
  •  北恋
    北恋 (楼主)
    2021-02-01 22:37

    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

提交回复
热议问题