简体   繁体   中英

A c# Generics question involving Controllers and Repositories

I have a base repository class which contains all the common repository methods (as generic):

public abstract class BaseRepository<T, IdType> : IBaseRepository<T, IdType>

My repositories from this base eg:

public class UserRepository : BaseRepository<User, int>, IUserRepository

I also have a base controller class containing common actions, and inherit from this in controllers. The repository is injected into this by DI. Eg

public class UserController : BaseController<User>
{
        private readonly IUserRepository userRepository;

        public UserController (IUserRepository userRepository)
        {
            this.userRepository= userRepository;
        }

My question is this: The base controller needs to be able to access the repository methods that are defined in the base repository. However I'm passing in via DI a different repository type for each controller (even though they all inherrit from the base repository). How can the base controller somehow access the repository that is passed in (regardless of what type it is), so that it can access the common base methods?

You can hold a reference for BaseReposiroty in BaseController

public class BaseController <T, IdType>
{
    ...
    ...
    protected BaseRepository<T, IdType> Reposirory
    {
        { get; set; }
    }
    ...
    ...
}

It all your repositories will be derived from IBaseRepository<T,IdType> , then have:

interface IUserRepository : IBaseRepository<User,int> {...}

Now any reference to a IUserRepository will know about the IBaseRepository<> members, without having to mention concrete types like the UserRepository class or BaseRepository<> class.

Here's one way to do it..

public abstract class BaseController<TEntity, TRepository, TIdType>
    where TEntity : class, new()
    where TRepository : IBaseRepository<TEntity, TIdType>
{
    protected TRepository Repository = RepositiryFactory.GetRepository<TEntity, TRepository>();

    public IList<TEntity> GetAll()
    {
        return Repository.GetAll().ToList();
    }
    public IList<TEntity> GetAll(string sortExpression)
    {
        return Repository.GetAll(sortExpression).ToList();
    }
    public int GetCount()
    {
        return Repository.GetAll().Count();
    }
    public IList<TEntity> GetAll(int startRowIndex, int maximumRows)
    {
        var results = Repository.GetAll().Skip(startRowIndex).Take(maximumRows);
        return results.ToList();
    }
    public IList<TEntity> GetAll(string sortExpression, int startRowIndex, int maximumRows)
    {
        var results = Repository.GetAll(sortExpression).Skip(startRowIndex).Take(maximumRows);
        return results.ToList();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM