Last post Jul 04, 2017 06:50 AM by AngelinaJolie
Jul 03, 2017 07:34 AM|bluMarmalade|LINK
After developing a big crup app, I realize that my controllers are too large with db code. So I want to implement a beginner friendly version of a repository to clean up my app and make it more testable.
I would love any input on how to do it and if this way of doing it is an ok way for a simple solution: I want to use entityframework for this first version, but i want to learn to use other orms in the future.
One thing i'm not sure about is how to implement the repository using dependancy injection. Do I have to make an interface for the repository in order to inject it into my controllers?
Like this in startup:
Then in controller the usual:
private ISqlRepository _repo;
public GjoremalController(ISqlRepository repo)
_repo = repo;
So then in the repo I inject the DbContext:
private ApplicationDbContext _context;
public SqlRepository(ApplicationDbContext context)
_context = context;
Do I have to use an interface to inject the repo into the controller, is it even good practice?
Jul 03, 2017 10:16 AM|hkholakiya|LINK
Yes you have to use interface into injection to access your repository in controller.
I used this pattern in my current project with multiple databases and it working fine and even flexible to change database connection for your whole application.
You can create common repository for all your entities in EF code first model.
Let me know if you have any specific question about this design.
Jul 04, 2017 06:50 AM|AngelinaJolie|LINK
Please refer to this more official example with repository pattern in asp.net core:
public class Repository<T> : IRepository<T> where T : BaseEntity
private readonly ApplicationContext context;
private DbSet<T> entities;
string errorMessage = string.Empty;
public Repository(ApplicationContext context)
this.context = context;
entities = context.Set<T>();
public IEnumerable<T> GetAll()
public T Get(long id)
return entities.SingleOrDefault(s => s.Id == id);
public void Insert(T entity)
if (entity == null)
throw new ArgumentNullException("entity");
public interface IRepository<T> where T : BaseEntity
T Get(long id);
void Insert(T entity);
void Update(T entity);
void Delete(T entity);
public void ConfigureServices(IServiceCollection services)
// Add framework services.
services.AddDbContext<ApplicationContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
And for more information ,please refer to the complete example: