Search code examples
c#sessionsession-statemulti-tenantsql-session-state

Switching Sql Session State databases


I have one instance of web application connected to multiple databases. Based on the domain name (for example www.shop1.com, www.shop2.com, ..) I switch the connection string in the Entity Framework.

shop1.com -> Database1

shop2.com -> Database2

shop3.com -> Database3

So far so good.

I am also using Sql Server session state and I want to switch the session state database just like I am switching database for my data.

shop1.com -> SessionStateDatabase1

shop2.com -> SessionStateDatabase2

shop3.com -> SessionStateDatabase3

Thanks in advance for your help.


More information if you want to know why I am doing this:

Actually I am implementing multi-tenancy. The description above shows three sites. In fact, I have more than 50. And the number of sites is going to grow in the next few months. At the moment all the sites are deployed separately which means whenever I have to roll out a patch or an update I deploy all 50 sites. Maintaining sites this way is becoming a nightmare. So I was thinking about putting 5 to 10 sites on one instance, depending on their usage, so that I have fewer instances to maintain.


Solution

  • In cases like this, I always look at the source code of the framework. First I find out where the configuration stores the session state connection string, then I find where it is being used. The private class System.Web.SessionState.SqlSessionState.SqlSessionStateStore has a method OneTimeInit(), where it reads the connection string. Here I noticed that there is support for partiniong, see here: http://msdn.microsoft.com/en-us/library/aa478952.aspx . I've never heard of this before, but it looks like it does exactly what you want, you can store session state in multiple databases, based on any kind of criteria you want. +1 for the question by the way, this is a cool feature. Also, if it doesn't work out, you could try implementing your own SessionStateStoreProviderBase implementation, which is publicly overridable.