I am building an MVC3 application and I am using Linq to sql for my DAL. My DAL is called MyDataReader and handles creating/initializing datacontext, plus it defines all the methods that retrieve data from the database. All the methods are instance methods, so in order to call the methods, I need to instantiate a MyDataReader object.
My questions is: what is the best way to call the methods in my DAL. Initially, I was instantiating a MyDataReader object from the controllers whenever I needed to call a DAL method. Then I realized every time I instantiate a MyDataReader object, the datacontext object is created and a connection gets established.
In my second approach, I created a static parameter in the Global.asax file as:
public class MvcApplication : System.Web.HttpApplication
{
public static MyDataReader reader;
protected void Application_Start()
{
reader = new MyDataReader();
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
This limits the database initialization operation to minimum. I can call the DAL methods from all my controllers by:
MvcApplication.reader.CallTheMethod()
Is this a good way? What is the best way to call DAL methods?