0

I've a BaseController but when I call the functions from the child Controllers the Context is always null:

public class BaseController : Controller
{
    private readonly TheContext _tContext;
    public BaseController(TheContext tContext)
    {
        _tContext= tContext;
    }

    public BaseController() { }

    public void test()
    {
        var foo = _tContext.BAR;
    }
}

I've been dealing with this by passing the Context to the BaseControler function from the child controller.

However, I now need to use OnActionExecuting() as there is code I need to run on load for each controller which uses the BaseController, which means I can't pass it the initialized context from the child controller.

Etheraex
  • 508
  • 6
  • 17
Vereonix
  • 1,341
  • 5
  • 27
  • 54
  • 1
    Have you tried using Dependency Injection? – Alexey Chuksin Jun 30 '21 at 14:37
  • `_tContext` is not accessible to classes derived from your `BaseController` because it is private. And why do you have two constructors? – Roar S. Jun 30 '21 at 14:52
  • I find inheritance is usually not the best pattern to use in cases like this. Methods like `test()` should be placed into a service that injects the context. Controllers that use the method should inject that service. Things that need to be done for each action should be placed in [action filters](https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-5.0). – StriplingWarrior Jun 30 '21 at 15:01
  • @AlexeyChuksin I'm blind ,I thought I had, but was missing the ": base(tContext)" in the child controllers. Works now ty – Vereonix Jun 30 '21 at 15:42

0 Answers0