mercredi 4 décembre 2019

Where put model mapper in a service for repository pattern

I want to have an explanation regard Repository Pattern and Services.

For service / repository layers is better if service methods must take an Entity model (Data layer) as argument or a different model

Example:

//Model DTO (came from another lib)
class User {
   public Name { get; set; }
   public OptionalValue { get; set; }
}

//Entity Model
class UserEntity {
   public ID { get; set; }
   public Username { get; set; }
   public GenericParameter { get; set; }
}

Here, I provide a UserEntity to Service, and service insert directly in DB.

Solution 1

Utility.cs
void execRoutine() {
    User user = someRoutineInAnotherLibs.getUser();
    var mappedUserEntity = Mapper.convertUserToUserEntity(user);
    serviceUser.saveUser(mappedUserEntity);
}


ServiceUser.cs
void saveUser(UserEntity u) {
    repo.insert(u);
}

Here, I provide a User to Service, that convert from a model to another model, then insert in DB.

Solution 2

Utility.cs
void execRoutine() {
    User user = someRoutineInAnotherLibs.getUser();
    serviceUser.saveUser(user);
}


ServiceUser.cs
void saveUser(User u) {
    var mappedUserEntity = Mapper.convertUserToUserEntity(user);
    repo.insert(u);
}

In each cases, I don't need to know implementation of User or UserEntity, because I have a mapper that know how to map one model to another model, so I think that I don't violate the SRP.

What's the most correct solution?

Aucun commentaire:

Enregistrer un commentaire