Search code examples
asp.net-core-mvcclean-architecturemediatrmediatoronion-architecture

Where layer should I put my ViewModel for ASP.NET Core 6


Good day fellow developers.

Sorry if this might not be a valid/confusing question as I am not that proficient with MVC.

With regards to clean architecture principle, what layer should I put my View Model? in entities layer? use case layer? or in presentation layer?

Some of the articles I found, they mentioned to put the ViewModel in Presentation layer but I am not sure how I can convert the data from DB to ViewModel if I put it in the mentioned layer.

Currently, this is my implementation. Converting the DB data to ViewModel using AutoMapper in the handler. Just to mention, I am using the Mediator design pattern using Mediatr.

FeatureController.cs

public class FeatureController : BaseController
{
  private readonly IMediator _mediator;

  FeatureController(IMediator mediator) {
   _mediator = mediator;
  }

  public IActionResult Method1() {
    var vm = _mediator.Send(new FeatureCommand())
    return View(vm);
  }
}

FeatureCommand.cs

public class FeatureCommand : IRequest<SomeViewModel>
{
}

FeatureCommandHandler.cs

public class FeatureCommandHandler : IRequestHandler<FeatureCommand, SomeViewModel>
{
    private readonly IMapper _mapper;
    private readonly ISomeRepo _someRepo;

    public void ViewModel(IMapper mapper, ISomeRepo repo) {
      _mapper = mapper;
      _someRepo = repo;
    }

    public async Task<DeviceWrapperDataView> Handle(FeatureCommand request, CancellationToken cancellationToken)
    {
        //Insert code to fetch data from DB
        var resultFromDB = repo.GetFromDB();

        return _mapper.Map<SomeViewModel>(resultFromDB);
    }
}

I am planning to create the ViewModels in different class library. Same level with the domain layer (inner part of the onion architecture) as for the reason that my UseCase layer needs to use those ViewModel shown in the return part of my Handler class.

Please correct me if my understanding with the clean architecture is wrong. Thank you in advance 🙂


Solution

  • According to Clean Architecture "true" ViewModels, so those objects which are send to the frontend, always belong to the "interface adapters" layer often also named "presentation layer".

    But as you are talking about "Converting the DB data to ViewModel" you probably rather mean "response objects" which belong to the use case layer or even "entities" which belong to the domain model.