3
\$\begingroup\$

Is it bad design if I create repostory with methods that returns generic types. For example in AccountsRepository if I have:

public class Repository<T> : IRepository<T>
where T : class
{
}

public class AccountsRepository<TUser> : 
Repository<User>,IAccountsRepository
    where TUser : class,IUser,new()
    {
      public TUser GetUserByUserName(string username)
      {
       return this.context.User.Where(s => 
       s.UserName.Equals(username)).Select(c=>new TUser(){ Password =c.Password }).FirstOrDefault();
      }
    }

Is this the proper way of doing that. So It's something like I return DTO object but it is generic type. So my classes using repository doesn't have to know what types are the objects in database.

\$\endgroup\$
  • \$\begingroup\$ I always find it hard to do in a good way. usually you end up having to create methods for a specific type, in your example the type "User" needs a method to find the user by name, most other types don't need that. \$\endgroup\$ – omaraloraini Jun 15 '17 at 22:29
  • \$\begingroup\$ What's IRepository<T>? What's the point in emptyRepository<T> implementation? What's User and how does it relate to IUser and TUser? Too much code is omitted, but if I guessed it right, it feels like this is going to be a needless level of abstraction. Your question lacks explanation on why you think this is necessary. \$\endgroup\$ – Nikita B Jun 16 '17 at 9:38
1
\$\begingroup\$

Is it bad design if I create repostory with methods that returns generic types.

Not at all. It's very useful.

Is this the proper way of doing that?

I'm not entirely sure because even though you use a generic return type you use the same User table for all of them:

this.context.User

However if the IRepository provides different User tables where each of the different users implement the TUser then I'd say it' fine. Otherwise it would not be that usefull and you could just return the normal User.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.