Search code examples
entity-frameworkdata-access-layer

Which layer should I place method to return current user's information?


I have a layered application. I am trying to determine where to place a method that returns an object populated with information about the active user. The layers are:

  1. Data Access Layer (Entity Framework)
  2. Domain Layer (POCOs)
  3. UI Layer (Web, Mobile, and Windows)

Which layer should I place the method in? This is the method:

    internal static User ActiveUser()
    {
        var name = System.Threading.Thread.CurrentPrincipal.Identity.Name;
        if (string.IsNullOrEmpty(name))
        {
            return null;
        }
        else
        {
            using (EfContext db = new EfContext())
            {
                return db.Users.Single(u => u.UserName.ToLower().Equals(name.ToLower()));
            }
        }
    }

Solution

  • My answer would be that "the" method should not exist. At least not as it is now. Getting the CurrentPrincipal name could probably be a function of your domain (domain service), or a separate application service, not the DAL.

    But the EfContext should not be visible to Domain, even less to UI. Common practice is to encapsulate it in a repository.

    So you domain/application service could "ask" your repository for a User by name.

    public User GetUser(string name)
    {
        using (EfContext db = new EfContext())
        ....
    }