My question is regarding caching and ViewModels in ASP.NET (Core) MVC.
I have a service which injects a Repository<T>
which is used to fetch domain models from the database. The service layer transforms the domain models into ViewModels via automapper and then caches them server side.
Example controller:
public FooController(IFooService service)
{
this.Service = service;
}
public IActionResult Index()
{
var vm = this.Service.GetSomeModel();
return View(vm);
}
Example service:
public FooService(IRepository<FooDomainModel> repository, IMapper mapper, ICacheService cache)
{
this.repository = repository;
this.mapper = mapper;
this.cache = cache;
}
public FooViewModel GetSomeModel()
{
var viewModel = this.cache.Get(some id);
if (viewModel == null)
{
var domainModel = this.repository.GetDomainModel();
viewModel = this.mapper.Map<FooViewModel>(domainModel);
this.cache.Add(viewModel);
}
return viewModel;
}
Is it considered bad practice for the service to transform the ViewModel
and cache it?
Should we instead cache the domain model only and then leave the responsibility of transforming to a ViewModel
up to the controller instead?
I feel like i'm saving a tiny bit of processing by caching the mapped ViewModel
in the service layer but there's some code smell here... mapping seems like it ought to be the job of the controller.
What is the consensus? Or is there a different pattern entirely that i should consider looking at?