覆盖属性冲突
本文关键字:冲突 属性 覆盖 | 更新日期: 2023-09-27 18:08:18
我有两个复杂的类:
public class BaseRepository<EntityType> where EntityType : class
{
protected northwindDataContext context = new northwindDataContext();
public EntityType Get(object id)
{
return context.Set<EntityType>().Find(id);
}
public EntityType Save(EntityType entity)
{
// Do generic save things
}
}
public class BaseService<EntityType> where EntityType : class
{
public BaseRepository<EntityType> repo = new BaseRepository<EntityType>();
public EntityType Get(object id)
{
// Do generic get entities
return repo.Get(id);
}
}
然后我有多个"服务"类,有时(并非总是)我需要"替换"存储库以添加一些"额外"功能。
public class UserRepository : BaseRepository<User>
{
public User Get(object id)
{
// Do specific user get including Role DP
return context.Users.Include("Role").Find(id);
}
}
public class UserService : BaseService<User>
{
public UserRepository repo = new UserRepository();
}
使用这种格式,UserService实例调用basererepository . get()而不是UserRepository.Get()。
我想要做的唯一方法是像这样复制代码:
public class UserService : BaseService<User>
{
public UserRepository repo = new UserRepository();
public User Get(object id)
{
// This call to UserRepository.Get()
return repo.Get(id);
}
}
真正的问题是,我有29个"存储库",所以我需要添加"Get(int)","Get(谓词)","Save(实体)","Save(IEnumerable)","Delete(实体)"answers"Delete(IEnumerable)",这使得一种尴尬的代码。
是否有任何方法可以替换BaseService中的属性"repo",以便BaseService方法调用repo子类?
听起来您真正想要的是BaseService<T>.repo
字段(它是一个字段,而不是属性—我不鼓励您使用公共字段,但那是另一回事)成为适合该类型的存储库。这很容易做到-只是不要在BaseService<T>
中创建它。相反,将它传递给构造函数链:
// Type parameter renamed to follow normal .NET naming conventions
public abstract class BaseService<T> where T : class
{
private readonly BaseRepository<T> repo;
protected BaseService(BaseRepository<T> repo)
{
this.repo = repo;
}
public T Get(object id)
{
// Do generic get entities
return repo.Get(id);
}
}
public class UserService : BaseService<User>
{
public UserService() : base(new UserRepository())
{
}
}
事实上,如果UserService
不提供任何其他值,您可能只需要Service<T>
,非抽象的,并带有公共构造函数来获取repo。然后使用:
var userService = new Service<User>(new UserRepository());
例如。