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

前端 未结 3 943
太阳男子
太阳男子 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:52

    Per suggestions from both Calc and Sir Rufo, this works.

     public abstract class BaseController : Controller
    {
        protected UserManager UserManager { get; }
        protected SignInManager SignInManager { get; }
        protected IConfiguration Config { get; }
        protected IEmailSender EmailSender { get; }
        protected ILogger AppLogger { get; }
    
        protected BaseController(IConfiguration iconfiguration,
            UserManager userManager,
            SignInManager signInManager,
            IEmailSender emailSender,
            ILogger logger)
        {
            AppLogger = logger;
            EmailSender = emailSender;
            Config = iconfiguration;
            SignInManager = signInManager;
            UserManager = userManager; 
        }
    
        protected BaseController()
        {
        }
    }
    

    The parameters still have to be injected into the inherited controller and passed to the base constructor

    public class TestBaseController : BaseController
    {
        public static IConfigurationRoot Configuration { get; set; }
    
        public TestBaseController(IConfiguration config,
            UserManager userManager,
            SignInManager signInManager,
            IEmailSender emailSender,
            ILogger logger) : base(config,userManager,signInManager,emailSender,logger)
        {
        }
    
        public string TestConfigGetter()
        {
    
            var t = Config["ConnectionStrings:DefaultConnection"];
            return t;
        }
    
        public class TestViewModel
        {
            public string ConnString { get; set; }
        }
        public IActionResult Index()
        {
            var tm = new TestViewModel { ConnString = TestConfigGetter() };
            return View(tm);
        }
    }
    

    So now all the injected objects will have instances.

    Was hoping the final solution would not require injecting the commonly needed instances into each inherited controller, only any additional instance objects required for that specific controller. All I really solved from a code repeating aspect was the removal of the private fields in each Controller.

    Still wondering if the BaseController should inherit from Controller or ControllerBase?

提交回复
热议问题