我在ASP.NET Core 2.0應用程序中實現存儲庫模式。帶有通用基類的ASP.NET Core 2.0存儲庫模式
我有一個BaseRepository類,如下所示:
public class BaseRepository<TEntity> where TEntity : class
{
private ApplicationDbContext _context;
private DbSet<TEntity> _entity;
public BaseRepository(ApplicationDbContext context)
{
_context = context;
_entity = _context.Set<TEntity>();
}
public IList<TEntity> GetAll()
{
return _entity.ToList();
}
public async Task<IList<TEntity>> GetAllAsync()
{
return await _entity.ToListAsync();
}
}
,我已經實現了兩個具體的存儲庫(我只是測試):
public class CourseSubjectRepository : BaseRepository<CourseSubject>
{
public CourseSubjectRepository(ApplicationDbContext context) : base(context)
{
}
}
public class ThemeRepository : BaseRepository<Theme>
{
public ThemeRepository (ApplicationDbContext context) : base(context)
{
}
}
CourseSubject和主題是代表實體POCO類在EF Core代碼中第一個數據庫。
讓所有可用的資源庫在一個地方,我已經實現了某種工廠(因爲它從DI容器實例孩子)的:
public class RepositoryFactory
{
public RepositoryFactory(IServiceProvider serviceProvider)
{
_provider = serviceProvider;
}
private IServiceProvider _provider;
public ThemeRepository GetThemeRepo()
{
return _provider.GetService<ThemeRepository>();
}
public CourseSubjectRepository GetCourseSubjectRepository()
{
return _provider.GetService<CourseSubjectRepository>();
}
}
現在在啓動configureService:
services.AddScoped<ThemeRepository>();
services.AddScoped<CourseSubjectRepository>();
services.AddScoped<RepositoryFactory>();
現在我有兩個問題:
1 .-這是實現和使用ASP.NET的核心Repository模式的一個好辦法嗎?
2.-我在我的數據庫中有很多實體,我想知道是否添加其存儲庫的唯一方法是爲它們中的每一個創建一個類,並使用.AddScoped將其添加到DI中。我的意思是,現在我有一個代表所有存儲庫的泛型類(它們將具有相同的方法),將類BaseRepository添加到DI並「以某種方式」使用類似下面的方式獲取具體的存儲庫實例會很好:
ControllerConstructor(BaseRepository<Theme> Themes)