I'm building a ASP.NET Core Web API and the application consists of 3 main modules.
- Data module: Contains the entities and
DbContext - Web API: Contains the controllers
- Service module: Contains all the data processing logic between the data module and the web API.
I'm not using repository pattern to access data from the service module, and I was thinking about fully exposing my DbContext to the service module to query it directly from the service module. Later, I created an interface and defined some methods to expose only the DbSet<T> or IQueryable<T> to its caller,
public interface IShareableContext
{
//option 1
DbSet<TEntity> ExposeDbSet<TEntity>() where TEntity : class;
//option 2
IQueryable<TEntity> ExposeIQueryable<TEntity>() where TEntity : class;
Task SaveChangesAsync();
}
internal class DefaultSharedContext : IShareableContext
{
private readonly ApplicationDbContext _ctx;
public DefaultSharedContext(ApplicationDbContext ctx)
{
_ctx = ctx;
}
public DbSet<TEntity> ExposeDbSet<TEntity>() where TEntity : class
{
return _ctx.Set<TEntity>();
}
public IQueryable<TEntity> ExposeIQueryable<TEntity>() where TEntity : class
{
return _ctx.Set<TEntity>();
}
public async Task SaveChangesAsync()
{
await _ctx.SaveChangesAsync();
}
}
And this interface and implementation will be registered on the dependency injection container to be used by the service module. But I'm still wondering whether should I choose option 1 method or option 2 method in my IShareableContext interface. Especially about returning a concrete class vs interface. If I'm returning IQueryable<T> I will have to define and implement some additional methods for behaviors such as add, delete and modify since IQueryable<T> does not define them. But I can't figure out whether staying away from returning DbSet<T> is worth for having to implement a few more behaviors.
IQueryablethat defines the extra methods that you need?IQueryable.