3

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?

4

It doesn't make sense to cache the ViewModel

ViewModel + View = HTML. So if your view model hasn't changed then the HTML hasn't changed. You can just return the cached page.

Cache the models, because they will be reused over multiple page requests to produce different results.

3
  • Makes sense. Should i move the mapping of domain model => viewmodel out of the service layer and into the controller? – Duane Jan 6 at 10:06
  • 1
    @Duane: I don't think there is consensus about where the mapping of domain model to view model should go. I've done it in the controller. I've done this in view model constructors, and a specialized "view model factory". To be honest, I haven't found a way I like better. – Greg Burghardt Jan 6 at 12:34
  • yes viewmodel creation should be in the controller. I would suggest the one2one view-viewmodel relationship pattern – Ewan Jan 6 at 14:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.