0

I am creating a web API in ASP.Net with IIS. However, I have been storing class members statically so that they can be accessed across different classes. This is obviously bad practice and I am noticing that every time a request is being made for the API, the same values are being returned due to the members not being cleared. How would I clear the members every request while also being able to access them across classes?

  • 3
    Don't make them static if they're only supposed to be in scope for a single request. You say you know you're not supposed to be doing it, so why are you asking how to keep doing the thing you know you shouldn't be doing? – Servy Aug 23 '18 at 17:10
  • How about create a separate (non-static) class which (non-statically) holds all the values that used to be static in the old class and then give every instance of the old class a reference to the current instance of the new class? And on a new call, create another instance of the new class with other values and give a reference to that to any object that needs it. – Corak Aug 23 '18 at 17:15
  • Don't (solely) "store" dependencies in your classes. These should be fed in from DI, where their scope (lifetime) can be explicitly controlled. – spender Aug 23 '18 at 17:19

1 Answers1

0

You should almost never use static variables in a web application. Even if you want to share variables across requests, access to statics is not thread-safe in many cases, and that can result in corrupt memory, incorrect system behavior, and even total system failure (if you're unlucky).

If you have variables that need to be shared, use an application variable instead. If you need to have a common cache, use one of the established caching techniques.

As for your specific question

How would I clear the members every request while also being able to access them across classes?

I think there is a misunderstanding here. There is no absolutely no reason to re-use a variable if it is being reset every time. I am guessing you think there is a performance cost to allocating new variables with each request; this is false. It is actually less efficient to use shared variables as multiple threads will experience false sharing and have to wait for each other as each request completes. If you use a new set each time, each thread has its own sandbox to work in and can complete the request much more quickly.

Instead, store your variables locally or as member variables in an object that is discarded at the end of the request. If you need some common location across all modules within a request, you can use HttpContext.Item or one of its alternatives.

John Wu
  • 50,556
  • 8
  • 44
  • 80