Introduction to Multi-Tenant Architecture
Have you ever built multiple websites that have similar core functionality but really differ only in a few ways, such as layout and UI? This can be costly and time consuming. Instead of copying and pasting code, giving it different namespaces, and then setting each to a different site name, I will discuss an architecture concept referred to as Multi-Tenant Websites, which helps improve upon the scenario I just mentioned. These websites allow developers to create a multitude of sites with slight discrepancies, while maintaining a shared code-base and appearing different to the end-user. I will go into the main concepts that the Multi-Tenant Architecture Utilizes and show some examples of these.
The first piece to start with is having a table in your database to map each tenant (NOTE: When I refer to "Tenant," this term can be used interchangeable with "Website" to limit confusion) to an ID. For this case, a simple Database Table with an Identity column and name of the tenant as shown in Figure 1 will be enough.
Figure 1: Table Containing List of Tenants using the website.
This Table will allow you to Map all tenant specific data to its proper tenant.
App URL and App Settings
This next piece is the most critical concept to successfully differentiate websites from each other sharing the same code base and, in most cases, the same database. From the first section, you might wonder how you determine which tenant is active as a user is navigating to its respective site. Well, you can utilize the URL string and create a mapping table of all the possible URLs for the web server and relate it to its corresponding tenant ID (I will demonstrate the mapping later on in the article). Figure 2 illustrates the table used for the mapping.
Figure 2: Table mapping URLs to a specific Tenant Id.
This table maps the "localhost" URL to load Tenant Id = 0.
One piece critical to a Web Application is utilizing the Web.Config to store global settings that can be configured easily and not hard-coded in the application. The problem with multiple websites sharing the same application is some app settings may be applicable to all of them but the value may need to be different. To handle this, I have created an App Settings table shown in Figure 3 that matches a group of app settings to a tenant.
Figure 3: App Settings Table Definition