Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8898531
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T00:38:10+00:00 2026-06-15T00:38:10+00:00

I am trying to code with best practices and I have a doubt here.

  • 0

I am trying to code with best practices and I have a doubt here. I am testing this on WebForms.

I have a UserService Layer where I have a method to pass a user to the RepositoryLayer:

public AddUserResponse AddUserResponse(AddUserRequest addUserRequest)         
{
  AddUserResponse response = new AddUserResponse();
  User objUser = new User();

  objUser.Names = addUserRequest.Names;
  objUser.LastName = addUserRequest.LastName;
  objUser.Email  = addUserRequest.Email;
  objUser.Alias  = addUserRequest.Alias;
  objUser.Profile.IdProfile = addUserRequest.Profile.IdProfile;
  objUser.Password = addUserRequest.Password;
  objUser.Active = addUserRequest.Active;

  short OperationState=_userRepository.Add(objUser);        
  if (OperationState==0)  
  {
    response.State=true;
    response.Message="User inserted";
  }
  else if (OperationState==2)
  {
    response.State=false;
    response.Message="Alias or Email already exist. Cannot insert User";
  }
  else 
  {
    response.State=false;
    response.Message="Error in User insertion";
  }       

  return response;           
}

Then I have a UserRepository Layer where I have a function that Adds a user comming from my service layer:

public short Add(User objUser)
    { ...  return OperationState  }

As showed this function relays on a stored procedure call to insert the user record. If the user email or alias doesn’t exist then it inserts and returns 0, if it does returns 2, and if the operation fails returns 1.

I perform the checking and insertion in one call to save database round trips.

Am I performing the checking in a correct way on my service and repository classes?, or if am not, How should I abstract the logic to let the system determine when is a duplicated user?. Should I use the model or service to put the validation logic and raise a custom exception when that happens?

Thanks a lot for your insight.

UPDATE

For general interest I am posting now how I am implementing this on my App, once I get the Jason’s IoC solution gonna make an update on this as well.

Model Class:

using ABC.DEF.Infrastructure.Domain;

namespace ABC.DEF.Model
{   
    public class AliasOrEmailAreUnique
    {
        private readonly IRepository<User, int> repository;

        public AliasOrEmailAreUnique(IRepository<User,int> repository) 
        {
            this.repository = repository;
        }

        //If the user is added has Id 0 so search among all the existing users for one that could have the alias or email registered already    
        //else if the user is being edit then search among all the user except the user with such Id(itself)
        public bool IsBroken(User model) 
        {
            if (model.IdUser == 0)
            {
                return (
                repository.List().Where(x => x.Alias == model.Alias).Any()
                || repository.List().Where(x => x.Email == model.Email).Any()
                );
            }
            else 
            {
                return (
                repository.List().Where(x => x.Alias == model.Alias && x.IdUser != model.IdUser).Any()                    
                || repository.List().Where(x => x.Email == model.Email && x.IdUser != model.IdUser).Any()
                );
            }


        }

        public ErrorMessage ErrorMessage
        { 
          get { return new ErrorMessage { Property = "AliasEmail", Message = "Alias or Email exists already" }; } 
        }
    }
}

Service Class:

using ABC.DEF.Repository;
using ABC.DEF.Model;
using ABC.DEF.Service.Messaging.User;

namespace ABC.DEF.Service
{
    public class UsuarioService
    {
        public AddUserResponse AddUserResponse(AddUserRequest addUserRequest)         
        {
            AddUserResponse response = new AddUserResponse();
            User objUser = new User();

            objUser.Names = addUserRequest.Names;
            objUser.LastName = addUserRequest.LastName;
            objUser.Email  = addUserRequest.Email;
            objUser.Alias  = addUserRequest.Alias;
            objUser.Profile.IdProfile = addUserRequest.Profile.IdProfile;
            objUser.Password = addUserRequest.Password;
            objUser.Active = addUserRequest.Active;


            //Determine if the Alias or Email are unique
            Model.AliasOrEmailAreUnique aliasOrEmailAreUnique = new Model.AliasOrEmailAreUnique(_userRepository);

            if (!aliasOrEmailAreUnique.IsBroken(objUser))
            {
            _usuarioRepository.Add(objUser);
            response.State = true;
            response.Message = "User added succesfully";
            }
            else
            {
            response.State = false;
            response.Message = aliasOrEmailAreUnique.ErrorMessage.Message;
         }

         return response;           
      }
   }

}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T00:38:11+00:00Added an answer on June 15, 2026 at 12:38 am

    I like to validate the input at the beginning of a unit of work. For a web application the request is the unit of work. before the controller action is fired I validate the user input. the action itself is the “happy path”. if it makes it this far I know my operation will succeed. at the end the request (the response) I commit any changes back to the database.

    I also like to keep my operation explicit so a call to add an entity would be different than call to edit an entity vs. deleting an entity.

    in your scenario you have a service layer rather than controller actions, but the process is still the same. validate the model before calling the service layer. then pass the model to the service layer to preform what operations you want.

    …UPDATE 1…

    in response to your comment below…..

    I have been calling my repositories only in the service layer

    Becareful not to fall into the trap of thinking there is a linear patterns for making calls. through the application. instead think of it as an onion or sphere with multiple layers.

    The model is just a POCO/DTO. there would be other components responsible for validating the model. typically I have a business rules engine that looks something like this… written off the top of my head.

    interface IRule<T>
    {
         bool IsBroken(T model);
         ErrorMessage Message {get;}
    }
    
    interface IRulesEngine
    {
         IEnumerable<ErrorMessage> Validate<T>(T model);
    }
    
    class ErrorMessage
    {
          public string Property {get;set;}
          public string Message {get;set;}
    }
    
    class RulesEngine : IRulesEngine
    {
         private readonly IContainer container;
         public RulesEngine(IContainer container)
         {
              this.container = container;
         }
    
         public IEnumerable<ErrorMessage> Validate<T>(T model)
         {
               return container
                         .GetInstances<IRule<T>>()
                         .Where(rule => rule.IsBroken(model))
                         .Select(rule =>  rule.Message);
         }
    }
    

    this implementation assumes an IoC container, but can be implemented without one. The a rule may look like this

    class NameIsUnique<MyClass> : IRule<MyClass>
    {
         private readonly IRepository<TheEntity> repository;
    
         public NameIsUnique<MyClass>(IRepository<TheEntity> repository)
         {
             this.repository = repository;
         }
    
         public bool IsBroken(MyClass model)
         {
              return repository.Where(x => x.Name == model.Name).Any();
         }
    
         public ErrorMessage 
         { 
             get { return new ErrorMessage { Property = "Name", Message = "Name is not unique" }; } 
         }
    }
    

    finally, how this can be used.

    var errors = engine.Validate(model);
    LoadErrorsInToView(errors);
    if(errors.Any()) return;
    
    //call service to process the happy path...
    

    …UPDATE 2…

    first we refactor our interfaces

    //this is just a marker interface. don't directly imeplement this.
    interface IRule
    {
    }
    
    interface IRule<T> : IRule
    {
        bool IsBroken(T model);
        ErrorMessage Message {get;}
    }
    
    class RulesEngine : IRulesEngine
    {
        public reasdonly ICollection<IRule> Rules = new List<IRule>();
    
        public IEnumerable<ErrorMessage> Validate<T>(T model)
        {
           return Rules
                     .Where(x => typeof(IRule<T>).IsAssignableFrom(x.GetType()))
                     .Cast<IRule<T>>()
                     .Where(rule => rule.IsBroken(model))
                     .Select(rule =>  rule.Message);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have been trying to figure out the best practices to write test-friendly code,
I'm trying to adopt some best practices to keep my python code efficient. I've
Im trying to find best practices to write PHP. I just wonder is this
I'm really trying to figure out the best practices for reusable code that is
I'm trying to teach myself the repository pattern, and I have a best practices
I am trying to understand the best practices for structuring an ember.js application. This
I am trying to implement Direct payment method as I have user's credit card
I'm trying to find the best way (in code) to determine the final destination
I am having an issue converting type. I was trying code like this (minimal,
I´m trying to code a tooltip (Yes I know, I have my reasons to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.