My controllers need to get data that is passed back to the view. Where should I open a connection to pass to the repository? Here is an example. This is a part of one of my controllers.
using (var connection = this.GetActiveConnection())
{
var repository = new RefRepository(connection);
var codes = repository.GetPoACodes();
}
Is it bad practice to be opening a connection in the controller? If I don’t pass it via the controller, where should I pass the connection to the repository?
Actually Repositories must handle connection themselves, it shouldn’t be controller concern.
Controller class must remain thin, and if it gets fat, it would be a code smell.
It would a very good practice if you can use a Dependency Injection Framework (like Ninject, StructureMap, …) to wire those dependencies , to handle DbContext or Session and SessionFactory (EF or NHibernate), Transaction or namely Unit of Work pattern, Exception Handling and Logging if you want to go thus far.
If you’re using Visual Studio then in Project Templates there is an option which create repositories also, you can create a sample project, read the code, and learn how the code is organized.
In this article, under Web API header, you can find out how to do it.