0
votes

I'm working with the ASP.net Web API for a simple REST api. I'm using Linq for my data access layer and was newing up a new linq datacontext for every api call. But it seemed a bit resource intensive to create a new data context for every call, so I started thinking about moving the datacontext to single application-level variable which would be instantiated in the global.asax.

Each api function is simply performing straightforward CRUD operations on a single table. I understand there are some concurrency issues if with this approach. But in reality all tables are partitioned by users so 2 different users could not update or delete the same rows on any table. Also since its an api I'm calling datacontext.submitchange() after every change so there any single user could update the same row at the same time.

So beside the concurrency issue, are there other concerns which managing a datacontext at the global level vs. instantiating on every api call? Are there other approaches that might also achieve the performance/resource benefits of the application-level instantiation?

1
What makes you think it's resource-intensive? Have you noticed a performance problem? This is known as a "premature optimization". - John Saunders
I'm using Azure so given the differences between the actual environment & my debugging platform, I'm sorta left to measuring the round trip of a single request & I'm more concerned about performance under load. My thought is linq has not only business logic but SQL connections that need to be instantiated & opened on every request. So multiplying that over 100s/1000s of requests has to be at least somewhat less performant than a single instantiation and connection opening. Although perhaps the overhead involved in the request web, api instantiation, etc make the incremental overhead trivial. - frigon
Ever hear of connection pooling? There may be no SQL connections opened on each request. Consider that Microsoft probably thought of this scenario already. - John Saunders

1 Answers

0
votes

I believe you can define your data context to be a global variable. If you are absolutely sure that in the future you will have no problem because of this, then you can do this.

However, before you make this change may I suggest that you benchmark your application to find out exactly what is eating your resources? Are you absolutely sure that your data context is guilty? What if something else eats your resources?

You should identify your problem first and only then start to optimize.