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
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?