Entity Framework:为仓储实现注册不同接口的疑问
仓储接口注册与方法访问问题
仓储类继承结构代码
public interface IReadOnlyRepository { public IEnumerable<TEntity> Get<TEntity>() where TEntity : BaseEntity } public interface IReadWriteRepository : IReadOnlyRepository { public void Add<TEntity>(TEntity entity) where TEntity : BaseEntity public void Update<TEntity>(TEntity entity) where TEntity : BaseEntity // more CRUD methods etc } public class Repository(DbContext dbContext) : IReadWriteRepository { public IEnumerable<TEntity> Get<TEntity>() where TEntity : BaseEntity { // implementation } public void Add<TEntity>(TEntity entity) where TEntity : BaseEntity { // implementation } // rest of CRUD method implementations }
服务注册代码
// Read write repo services.AddScoped(typeof(IReadWriteRepository), p => new Repository(p.GetRequiredService<DbContext>())); // Read only repo services.AddScoped(typeof(IReadOnlyRepository), p => new Repository(p.GetRequiredService<DbContext>()));
问题
即便Repository类包含所有CRUD方法的实现,当将其注册为IReadOnlyRepository类型时,是否仅能访问Get()方法?若如此,其他CRUD方法会处于何种状态?是否不会被包含在只读版本的Repository实例中?
回答
- 当从DI容器获取
IReadOnlyRepository实例时,只能直接访问该接口定义的Get()方法——编译器会将实例视为IReadOnlyRepository类型,仅暴露该接口声明的成员。 - 其他CRUD方法依然存在于实例内部,并没有被移除。Repository类的实例本身完整包含了所有方法的实现,只是因为你用
IReadOnlyRepository类型引用它,编译器会限制调用范围。 - 如果通过强制类型转换(比如将
IReadOnlyRepository转为Repository或IReadWriteRepository),仍然能调用那些CRUD方法,但这完全违背了“只读仓储”的设计初衷。
内容的提问来源于stack exchange,提问作者dbm
相关产品推荐
相关产品推荐

