In an asp.net core mvc project, i have an abstract ViewModel class, for a layout, which requires some properties to function properly, and each concrete page's ViewModel derives from it:
public abstract class Layout
{
// required to function properly
public string Prop1 { get; set; }
// required to function properly
public IEnumerable<Foo> FooList { get; set; }
protected Layout()
{
// Populate FooList from an util caching class?
}
}
public class ViewModelHome : Layout {}
public class ViewModelProducts : Layout {}
The layout requires a FooList, which is populated from a database or a cache, since it is data not often changed.
I would like to avoid to putting each required field in the constructor in order to make it not too verbose, and I would like to avoid the following for each derived class:
var model = new ViewModelHome();
model.FooList = .....
In asp.net core caching is available through DI of IMemoryCache, so I cannot write something like this:
public abstract class Layout
{
protected Layout()
{
var cacheClass = new MyCacheClass(...IMemoryCache??...);
this.FooList = cacheClass.GetFooList();
}
}
This is because I'm creating Layout on my own in a service, in turn called from controllers.
public class MainController : Controller
{
private readonly IMainService _service;
public MainController(IMainService service)
{
_service = service;
}
public IActionResult Home()
{
return View(_service.GetHomeViewModel());
}
public IActionResult Products()
{
return View(_service.GetProductsViewModel());
}
}
My question is: should i put in the abstract class constructor the logic for getting data from database or cache?
Thanks