我下面嘗試Repository模式實現解決歧義
interface IRepository<T>
{
IQueryable<T> All { get; }
T Find(object id);
void Insert(T model);
}
那麼我IAdminRepository定義如下
interface IAdminRepository : IRpository<Role>, IRepository<User>
{
}
public class AdminRepository:IAdminRepository
{
IQueryable<User> IRepository<User>.All
{
get { throw new NotImplementedException(); }
}
User IRepository<User>.Find(object id)
{
throw new NotImplementedException();
}
void IRepository<User>.Insert(User model)
{
throw new NotImplementedException();
}
IQueryable<Role> IRepository<Role>.All
{
get { throw new NotImplementedException(); }
}
Role IRepository<Role>.Find(object id)
{
throw new NotImplementedException();
}
void IRepository<Role>.Insert(Role model)
{
throw new NotImplementedException();
}
}
在我的業務層,我使用基於接口調用。
public interface IAdminService
{
bool CreateUser(User user);
List<User> GetAllUsers();
}
public class AdminService : IAdminService
{
private readonly IAdminRepository AdminRepository;
public AdminService(IAdminRepository _adminRepository)
{
AdminRepository = _adminRepository;
}
public bool CreateUser(User user)
{
AdminRepository.Insert(user);
return true;
}
public List<User> GetAllUsers()
{
return AdminRepository.All; // Here is error
}
}
Error: Ambiguity between IRepository.All & IRepository.All.
如何解決這個問題?以這種方式使用Repository Pattern的方法有什麼問題?
您的IAdminRepository從IRepository繼承IRepository ,因此當您執行AdminRepository.All時,它不知道應該調用哪個.All,因爲它同時具有用戶和角色。你應該做的是讓你的IAdminRepository類型T並繼承IRepository –
2013-03-15 09:59:26
@ManishMishra,你是說AdminRepository?它在這裏沒有任何意義:) –
Billa
2013-03-15 10:04:57