I'm using ILogger<T> and want it to be included in my base controller since every controller should use it.
I'm defining each derived class as UsersController : BaseController<UsersController>
In my base class I'm assigning ILogger<T> which works fine until I try to access the controller in my ActionFilter which I need to know how to cast it.
How do I achieve this or do it in a better way that accomplishes the same thing.
// Base Controller
public class BaseController<T> : ControllerBase
{
protected readonly IOptions<AppSettings> _appSettings;
protected readonly ILogger<T> _logger;
}
// Instance Controller
public class UsersController : BaseController<UsersController>
{
public UsersController(ILogger<UsersController> logger,
IOptions<AppSettings> appSettings)
: base(logger, appSettings)
{
...
}
// ActionFilter used to set viewbag on all pages/layout pages
public class ViewBagActionFilter : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext context)
{
// Can't use typeof() or nameof()
if (context.Controller.GetType().BaseType.Name == "BaseController")
{
// This doesn't work either
var controller = context.Controller as BaseController;
controller.ViewBag.Username = controller?.User?.Username;
}
base.OnResultExecuting(context);
}
}