I would like to create a repository for queries. For that, I was thinking of doing something like this:
public interface ICarsQueryRepository
{
public GetCarById(long Id);
//Another methods of repository.
}
public class CarsQueryRepositorySqlServerEntityCore8: ICarsQueryRepository
{
private readonly ContextoConsultasPedidosCompras _context;
//I inject IGetConnectionString to get the connection string, so I can create the dbContext here.
public CarsQueryRepositorySqlServerEntityCore8(IGetConnectionString paramConnectionString)
{
//La configuarción que tendrá el dbContext
DbContextOptionsBuilder<CarsContext> miBulider = new DbContextOptionsBuilder<CarsContext>();
miBulider.UseSqlServer(paramConnectionString);
_contexto = new CarsContext(miBulider.Options);
}
public GetCarById(long paramId)
{
//do something using _context.
}
}
Here, I am creating the dbContext in the constructor of the repository.
Normally, it is recommended not to create resources in the same class. It is better to inject them, mainly for two reasons: lower coupling, because I can change the implementation, and easier testing.
Regarding coupling, I think a repository is tied to a version of the dbContext. So, if I want to test the repository, I want to test if it works with this dbContext. I will not have tests that use mocks for another implementation. If I want to use another version of the dbContext, I would implement another repository, because there would be changes that break compatibility.
I think it is the consumer of the repository who needs to be injected with the interface of the repository to be able to use it.
I think that in this way, I have the benefit that the consumer doesn’t need to know the implementation of the repository. It doesn’t matter if the repository uses Entity Core, ADO.NET, or another technology.
I mention this because, in many code examples, I have seen the main application register the dbContext as a dependency to be injected into the repository. I think this increases the coupling, as I am coupling the main application to a specific version of the dbContext. Additionally, this makes the main application aware of the repository’s implementation, which raises the question: why?
In summary, I am wondering if it is really a bad idea to create the dbContext in the repository instead of registering the dbContext in the dependency injection manager to inject it into the repository.
Thanks.