سؤال

I am using MVC pattern abstracted with domain layer. I could convert a domain object into its equivalent DTO and sending it across top layer (ie controller & ultimately to views). Now how to do the reverse? How & where will I construct the actual DTO object and pass it to the controller?

هل كانت مفيدة؟

المحلول

I have found the best way to do this is have a DTO service layer. This will be a collection of functions that the controller (or anything else) can call to retrieve and convert DTO's.

I would also recommend doing the domain object to DTO mapping (and the reverse) in this layer too, it keeps all the DTO related logic in one layer.

Below is an example of a DTO service layer function:

        public CustomerDto GetCustomer(Guid customerId) {

        var roService = new RoService<Customer>(new Repository<Customer>(_dbContextFactory));
        return _mapper.ToCustomerDto(roService.Get(customerId));
    }

This will retrieve a Customer entity by its Id. The entity is passed to a mapper object which will convert it to a CustomerDto for it to be returned.

N.B. I used AutoMapper to convert my domain objects to DTO's.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top