Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best place to create global object in ASP.NET MVC

I would like to implement ConcurrentQueue object in my ASP.NET MVC app. The ConcurrentQueue object will be shared between sessions and should be created once. What is the best place to create ConcurrentQueue in ASP.NET MVC?

like image 357
Tomas Avatar asked Feb 29 '12 13:02

Tomas


People also ask

Which state is used for global application in C#?

Handling Global State in C# Applications. $ @"Processing complete. The ProcessDocuments method goes through an array of document ids, and calls a method called ProcessDocument on each document id. The ProcessDocument method processes a single document.

Where are global variables stored in C#?

C# do not support global variables directly and the scope resolution operator used in C++ for global variables is related to namespaces. It is called global namespace alias.

How do I create a global variable in razor view?

To declare a variable in the View using Razor syntax, we need to first create a code block by using @{ and } and then we can use the same syntax we use in the C#. In the above code, notice that we have created the Code block and then start writing C# syntax to declare and assign the variables.

How do you make something global in C#?

However, you can make a global variable by creating a static class in a separate class file in your application. First, create a class called global in your application with the code given below. The class also has a static variable. Now, you can access it from anywhere in your forms after assigning a value to it.


3 Answers

Any class you choose can hold an instance of it, however it would make most sense to couple it within a class that is responsible for whatever functionality the queue is used for.

For example a Cache class:

public class MyCache
{
     public static ConcurrentQueue Queue { get; private set; }

     static MyCache()
     {
          Queue = new ConcurrentQueue();
     }
}

This will initialize it the first time the MyCache class is used. If you want finer grain control, you could create an Initialize method that your Global.asax.cs file calls on app start.

like image 92
Chris S Avatar answered Oct 22 '22 09:10

Chris S


You could:

  1. Create it in a static constructor, so it's created only when some code actually uses the type
  2. Global.asax.
  3. Use WebActivator - you won't pollute Global.asax file, and you can create the queue in different assembly.
like image 37
Jakub Konecki Avatar answered Oct 22 '22 11:10

Jakub Konecki


File Global.asax.cs, protected void Application_Start() method overload.

Another approach would be making a Singleton/static class.

like image 35
Sergey Kudriavtsev Avatar answered Oct 22 '22 11:10

Sergey Kudriavtsev