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"];
}