I got lost while building generic repository with entity framework which has multiple contexts in my asp.net core 2 api project.
What I need is to inject my repository to controller without knowing which context it is using.
DbContext
public interface IDbContext
{
}
public interface IBlogContext : IDbContext
{
}
public interface IBlogLogContext : IDbContext
{
}
Repository
public class EfRepository<TEntity> : IRepository<TEntity> where TEntity : class, IEntity
{
private readonly IDbContext _context;
private readonly DbSet<TEntity> _dbSet;
public EfRepository(IDbContext context)
{
_context = context;
_dbSet = _context.Set<TEntity>();
}
/* other stuff */
}
Startup
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BlogContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
.UseLoggerFactory(_logger);
});
services.AddDbContext<BlogLogContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});
services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));
services.AddScoped<IBlogContext, BlogContext>();
services.AddScoped<IBlogLogContext, BlogLogContext>();
services.AddUnitOfWork<BlogContext, BlogLogContext>();
}
Controller
public class UserController : Controller
{
private readonly IRepository<User> _repository;
private readonly IAuthorService _authorService;
private readonly ILogger<UserController> _logger;
public UserController(IRepository<User> repository, IAuthorService authorService, ILogger<UserController> logger)
{
_repository = repository;
_authorService = authorService;
_logger = logger;
}
}
When I inject IRepository<User>
in controller constructor, how .net core DI resolve that User
is BlogContext
's entity, so IDbContext
should be BlogContext
inside my EfRepository
implementation?