-1

I have an object that contains a connection to an external service. The connection needs to be initialized once when a user logins, otherwise the service will throw an error when the connection is re-initialized.

The connection then needs to be open all the time and should available to multiple controllers that will call the service.

I am using ASP MVC & C#. I am currently initializing the variable when a user session starts and stores it in the user session as well. I am wondering if there are other alternatives to this approach.

Initializing the session variable

protected void Session_Start(object sender, EventArgs e)
{
    HttpContext.Current.Session.Add("SomeConnection", new SomeConnection());
}

Then I use an extension method that retrieves the connection from the session

public static SomeConnection GetSomeConnection(this HttpSessionStateBase session)
{
    return (SomeConnection) HttpContext.Current.Session["SomeConnection"];
}
  • take a look at this SO post [MVC Global Variables](https://stackoverflow.com/questions/5118610/asp-net-mvc-global-variables) – MethodMan Nov 23 '17 at 17:35
  • updated my question with the code – Richard Padre Nov 23 '17 at 17:44
  • storing it in a static variable will not work because each connection should be unique for each users, not shared – Richard Padre Nov 23 '17 at 17:45
  • when you put break points in the `Session_Start` method, does it hit that code? also where are you assigning the return value of the `SomeConnection` method value? instead of adding I would expect to see `=` vs adding.. `HttpContext.Current.Session["SomeConnection"] = (SomeConnection) HttpContext.Current.Session["SomeConnection"];` I would expect to do it this way – MethodMan Nov 23 '17 at 17:47
  • yeah, my current code actually works. I'm only looking for other possible solutions for this if I don't want to store my connection in a session. – Richard Padre Nov 23 '17 at 17:50
  • change the static method to either be an Instance method or a protected method – MethodMan Nov 23 '17 at 17:51
  • 1
    *"I am wondering if there are other alternatives to this approach."* I'll bet there is at least one alternative, and probably many more. However, that's exactly what the `Session` is for, since the happy days of ASP3 (and probably even before that) - Keeping data scoped to a specific client, as long as that client is still "connected" to the website. You are doing it right. – Zohar Peled Nov 23 '17 at 18:39
  • cool, good to know. thanks man! – Richard Padre Nov 23 '17 at 19:15

1 Answers1

0

Another approach is: If you are deploying on load balanced servers, to make this approach work you have to ensure session stickiness.

Otherwise you can use AppFabric to store your object in an independent server and make it available to all your servers. This way you will also be initializing your object only once.

Use GetExistingOrSet method.

Sunil
  • 3,404
  • 10
  • 23
  • 31