Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does each request in ASP.NET MVC, share static variables with other requests?

Tags:

asp.net-mvc

Can I store my active Entity framework Database Context for the request, as a static property somewhere, so it's easily fetchable from Validators, helpers etc.

**E.G set it from a global action filter onto a static class as

public static DBContext GlobalHelper.ActiveDbContextForRequest;

Does each request share these static properties though? If they do I suppose it cannot work.

like image 463
williamsandonz Avatar asked Oct 25 '25 00:10

williamsandonz


2 Answers

Yes, static variables are shared across the entire application (over all threads). You cannot safely access these variables without synchronization from various requests (since each request is handled on a different thread).

Even if you synchronize access to these variables, there's only a single instance of the static variable so all threads will see the same value - you can't have request-specific values this way.

like image 96
xxbbcc Avatar answered Oct 28 '25 00:10

xxbbcc


Static variables are global for the whole application domain by default so the answer is yes, they are shared by all requests served by it.

like image 27
Claudio Redi Avatar answered Oct 28 '25 02:10

Claudio Redi