mardi 19 mai 2020

Service model seperation

I'm following a service model separation approach between different layers of my application. As I'm using EntityFramework I've decided that creating repositories in the Data layer to return full entity models would be stripping and leaking data to the service layer.

I have 2 separate models, 1 for DAL and the other for the service layer to keep these layers abstract. You can see an example on how I achieved this below:

public class UserService : IUserService
{
    private readonly IAppUserManager<User> _appUserManager;

    public UserService(IAppUserManager<User> appUserManager)
    {
       _appUserManager = appUserManager;
    }

    public void Register(AccountRegister accountRegister)
    {
       var user = new User
       {
          FirstName = accountRegister.FirstName,
          LastName = accountRegister.LastName,
          Email = accountRegister.Email,
          UserName = accountRegister.UserName
       };
       _appUserManager.Create(user, accountRegister.Password);
    }
}

The User in this example is a service model. When the _appUserManager.Create() is called this converts the User model into a DAL ApplicationUser like so:

 public class AppUserManager : IAppUserManager<User>
 {
    private readonly UserManager<ApplicationUser> _userManager;

    public AppUserManager(UserManager<ApplicationUser> userManager)
    {
       _userManager = userManager;
    }

    public async void Create(User user, string password)
    {
       var applicationUser = new ApplicationUser
       {
          FirstName = user.FirstName,
          LastName = user.LastName,
          Email = user.Email,
          UserName = user.UserName
       };

        var result = await _userManager.CreateAsync(applicationUser, password);
     }
}

As you can see the AppUserManager maps a User to ApplicationUser and then uses Identity UserManager to create a user. Everything in this class should return User the service model and none of the DAL objects.

My question is, at the top level (DAL) what is the best way to bubble up error messages from the CreateAsync method? And would you say this is a good approach to prevent a leak of any DAL objects?

I just feel the AppUserManager is unneccessary and I should just use the UserManager in the UserService what do you guys think?

I'm open to opinions so please feel free to share some expertise!

Aucun commentaire:

Enregistrer un commentaire