Reputation: 25
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?
Upvotes: 0
Views: 161
Reputation: 93434
No, this is the absolute worst way to do it. The biggest reason is that static objects are shared between all concurrent users. That means multiple users adding, removing, querying the same context. This is a recipe for disaster, and will probably cause data corruption.
The other problem is that data contexts are designed to be short lived, so they do not manage their internal caches and lists, they just assume you will dispose of them when you are done with an operation.
You do not need to worry about connection management. Internally, this is managed in a connection pool, and .net will automatically reuse connections and dispose of them when they are idle for a period of time.
Don't pre-maturely optimize. You are usually wrong.
Upvotes: 2