Reputation: 44
Is it correct to instantiate classes and save them in Application variables to then use them and not have to instantiate them in each request?
For example: Instanciate a DbContext and use it directly from de Application variable every time I need.
And this means a real improvement in performance?
In the global asa:
protected void Application_Start()
{
Application["db"] = new Models.dbContext();
}
Using then:
db = (dbContext)HttpContext.Current.Application["db"];
Upvotes: -1
Views: 50
Reputation: 1368
DbContext
s should almost always be instantiated and discarded as needed. Connection-pooling and various other behind-the-scenes optimizations mean that this is quite efficient. Otoh, if you're using HttpClient
, you should probably aim to create a single one for all calls (as it can't perform connection keep-alive otherwise). It's up to you whether you store in an "Application" variable or just as a global static. But HttpClient is the exception - unless you need to maintain state for the lifetime of your application, or there's some very implementation-specific reason, there are good reasons to avoid having variables with global scope and/or lifetime.
Upvotes: 1