0

I am using the latest release of entity framework 4 - CTP 4 for my project in ASP.NET 4. This version (EF4-CTP 4) gives an option to build the Object Context (or DBContext) using code first approach. This approach has its own drawback that its time consuming so I build it up once at the application start. However I read in many articles that it may not be wise to create a singleton object of Object Context. So I wish to maintain small context instance may be per session.

So my questions are: 1. Is it advisable to have Object Context shared accross multiple session? 2. If we wish to have one instance per session can we build it once and use its instance for multiple sessions? 3. If shared accross session how can we maintain concurrency/commits?

Thanks.

Abhay Naik
  • 410
  • 3
  • 15

1 Answers1

3

I would suggest not to use a Singleton. Here's a SO question discussing why.

This also depends on whether this is a web/windows app, but with web apps, we scope the OC to the HttpContext using a DI container.

That way, only one connection is opened per HTTP Request.

Community
  • 1
  • 1
RPM1984
  • 72,246
  • 58
  • 225
  • 350
  • And yes, Shimmy has a good point - not sure what you mean by "across multiple session" – RPM1984 Nov 10 '10 at 04:45
  • Thanks for the quick one RPM1984/Shimmy. My issue is with building the OC which has a performance impact. Is it possible that I build the context once [at application start] and use its instance (even per request will work). – Abhay Naik Nov 10 '10 at 05:20
  • Not sure what you mean by "build the context". I have a custom OC too, but i "new" it at the beginning of request, and dispose of it at the end of request. What do you mean by "build"? – RPM1984 Nov 10 '10 at 05:48
  • Ok i will explain my situation a little bit more. In my application, I add the entities from an assembly. What assemblies to load in OC is stored in config file. It contains a list of assemblies which contains the implementation of contract "IEntity" which I created. I read through the types in assembly and those who implement IEntity, I Register the entity with OC. This process is time consuming as the number of entities will increase. This is what I meant by building the context. This is done at application start. Can I instantiate this model per request?? – Abhay Naik Nov 10 '10 at 06:23
  • Right, fair enough - not sure exactly *why* your doing this, but i guess that's another issue and your prerogative. Yes, what you can do is **create** the OC during Begin_Request, and **dispose** of it during End_Request. But as i said, it's made easier with a DI container. If your not willing to use a DI container, you'll have to implement some kind of factory pattern where your classes can access the OC that was created by Global.asax. Does that make sense? – RPM1984 Nov 10 '10 at 08:25