I've developed a generic repository pattern with EF Core (GenericRepository.cs), but want to extend this by adding it to multiple databases.
GenericRepository.cs
public class GenericRepository<TEntity, TContext> : IGenericRepository<TEntity> where TEntity : class where TContext : DbContext
{
private readonly TContext _context;
public GenericRepository(TContext context)
{
_context = context;
}
public TEntity GetById(string id)
{
return _context.Set<TEntity>().Find(id);
}
...
}
With that in mind I then made the ContextRepository.cs generic by adding a TContext to the class. This only worked if the context class was of type DbContext.
ContextRepository.cs
public class ContextRepository<TContext> : IContextRepository where TContext : DbContext
{
private readonly TContext _dbContext;
private readonly Dictionary<Type, object> _repositories = new Dictionary<Type, object>();
public Dictionary<Type, object> Repositories
{
get { return _repositories; }
set { Repositories = value; }
}
public ContextRepository(TContext dbContext)
{
_dbContext = dbContext;
}
public IGenericRepository<TEntity> Repository<TEntity>() where TEntity : class
{
if (Repositories.Keys.Contains(typeof(TEntity)))
{
return Repositories[typeof(TEntity)] as IGenericRepository<TEntity>;
}
IGenericRepository<TEntity> repo = new GenericRepository<TEntity, TContext>(_dbContext);
Repositories.Add(typeof(TEntity), repo);
return repo;
}
}
Here's the issue:
I have two different database contexts (ApiAuthorizationDbContext and DbContext).
Is there a way/workaround to achieve this with both contexts in the same generic context class?
DbContextis a unit of work and eachDbSetis a repository.