IService extends IRepository correct?
本文关键字:correct IRepository extends IService | 更新日期: 2023-09-27 18:10:57
说我的IService拥有IRepository拥有的一切是正确的,还有更多一些特定的操作?
代码如下:
public interface IRepository<T>
{
T Add(T Entity);
T Remove(T Entity);
IQueryable<T> GetAll();
}
public interface IUserService
{
//All operations IRepository
User Add(User Entity);
User Remove(User Entity);
IQueryable<User> GetAll();
//Others specific operations
bool Approve(User usr);
}
注意IRepository
中的所有操作也都是IService
。
这是正确的吗?
如果是这样,最好这样做:
public interface IUserService : IRepository<User>
{
bool Approve(User usr);
}
另一个选项是:
public interface IUserService
{
IRepository<User> Repository { get; }
//All operations IRepository
User Add(User Entity);
User Remove(User Entity);
IQueryable<User> GetAll();
//Others specific operations
bool Approve(User usr);
}
public class UserService : IUserService
{
private readonly IRepository<User> _repository;
public IRepository<User> Repository
{
get
{
return _repository;
}
}
//Others specific operations
public bool Approve(User usr) { ... }
}
注意,我把存储库作为一个属性,并且在我的服务类中公开了这个属性。
所以如果你需要添加,删除或在仓库中获取一些对象,我可以通过这个属性访问它。
你怎么看?这样做对吗?
你可能已经为自己解决了这个问题,但我还是要提供一个意见。
第二个例子:
public interface IUserService : IRepository<User>
{
bool Approve(User usr);
}
是你应该使用的——它很漂亮,很干净。在你的第一个例子中,IUserService
中包含的大多数东西都是完全多余的,IUserService
实际上只添加了bool Approve(User usr)
。您还会发现,如果您使用第二个示例,当您添加UserService
并让Visual Studio自动实现IUserService
时,您最终会得到以下内容:
public class UserService : IUserService
{
public bool Approve(User usr)
{
throw new NotImplementedException();
}
public User Add(User Entity)
{
throw new NotImplementedException();
}
public User Remove(User Entity)
{
throw new NotImplementedException();
}
public IQueryable<User> GetAll()
{
throw new NotImplementedException();
}
}
public class User { }
public interface IRepository<T>
{
T Add(T Entity);
T Remove(T Entity);
IQueryable<T> GetAll();
}
public interface IUserService : IRepository<User>
{
bool Approve(User usr);
}
您可以看到,这些类型都为您正确填充,而无需在IUserService
中做任何额外的操作。