mattbloke
mattbloke

Reputation: 177

is this correct usage of dbcontext?

I have an MVC4, EF web application.

I have a data access class ("db_calls") that has all my methods for data access.

In each of my controllers I instantiate this class once with:

private db_calls dbcalls = new db_calls();

This "db_calls" class instantiates the dbcontext in order to work with the data like so:

private MyContext db = new MyContext ();

I have 3 questions:

  1. Everytime I access a db_calls method from my controller e.g. db_calls.getrecord() does it instantiate the class again or just once per controller?
  2. When I hit another controller, does it get rid of the previous instantiation of db_calls and start another one?
  3. Similarly, does the db_calls class itself instantiate the context each time for a method or does it do it only once?

My concern is that I am going to have a load of objects floating about that I dont need.

Upvotes: 0

Views: 51

Answers (1)

Ashish Charan
Ashish Charan

Reputation: 2387

I think whenever you use the "new" keyword a new object is created in memory.

  1. Only once per controller if instantiation code is written outside methods.
  2. Yes
  3. Yes, whenever you creAte a new db_calls it will create a new context.

Also I think your case is not too much non-optimized.

Upvotes: 1

Related Questions