Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pros and Cons of putting a db context in static class library

We have a static class library to deal with repeated multi-contextual tasks. Is it bad practice to create an EF db context as member of a static class?

DB contexts are meant to be disposed of for a reason. Having them disposed frequently keeps the connection pool "flowing" and probably (here I'm speculating) assures that tables don't remain locked.

So am I inviting trouble having a db context in a static class or am I overthinking this?

like image 699
Dave Alperovich Avatar asked Jan 25 '13 16:01

Dave Alperovich


2 Answers

IMO this is definitally not something you want to be doing.

Locking isn't actually the main problem you are going to have here. EF will only lock for the duration of a save changes call (its actually one of the big benefits of using a tracking graph over partially committed transactions which most other ORMs use).

What is going to cause you greif is the tracking graph itself. How EF works (in most cases) is that it keeps a copy of every entity its ever seen and loops through them to find whats changed and run a process called fixups which makes navigation properties work with backlinks. This process loops through every entity the context has ever seen and is called on a bunch of operations (add, attach, delete, save, query and a few others). This means if the tracking graph is large, this process can take quite a bit of time. If you keep your context alive forever the tracking graph size tends toward the size of your database, making it unwieldy and slow.

like image 126
Not loved Avatar answered Sep 17 '22 18:09

Not loved


It depends on many things, but here are some thoughts e.g.:

  • If you're using EF on service layer - then the concurrency might be an issue as I don't think that using EF context is thread safe, ie that you can use it from all threads at the same time without problems
  • If you have your entities tracked by the context (and I think even if you don't), the context would in time get quite large, eventually it could contain all of your database entities and then you'll run into performance problems

Either way, I think it's a bad idea.

like image 26
veljkoz Avatar answered Sep 17 '22 18:09

veljkoz