Tomas
Tomas

Reputation: 18097

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?

Upvotes: 6

Views: 4141

Answers (3)

Chris S
Chris S

Reputation: 65426

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.

Upvotes: 8

Jakub Konecki
Jakub Konecki

Reputation: 46008

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.

Upvotes: 3

Sergii Kudriavtsev
Sergii Kudriavtsev

Reputation: 10487

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

Another approach would be making a Singleton/static class.

Upvotes: 2

Related Questions