I have an application built using CodeFluent that is hosted as a SAAS solution. It uses the Ms Azure database as storage but all customers are in the same database now. Considering best practices for SAAS solutions it would be better to separate databases. It would be easier to backup/restore separate client data and also better from a security perspective. We would like to use the Azure elastic database pool.
However, it is not really simple. Codefluent uses a fixed database connection, set in the web.config. And if I can change it somehow, how can I determine what database to use. There is not always a session or httpcontext... Has anyone had the same challenge, and how did you solve it?
You’ll have one database per user. This means you need to change the connection string before you make a query to the database. With CodeFluent Entities you can change the connection string at runtime:
CodeFluentContext context = CodeFluentContext.Get(MyApp.Constants.MyAppStoreName);
CodeFluentPersistence persistence = context.Persistence;
persistence.ConnectionString = GetCurrentTenantConnectionString();
var products = ProductCollection.LoadAll();
Or you can create a custom CodeFluentPersistence
:
public class MultiTenantPersistence : CodeFluentPersistence
{
public MultiTenantPersistence(CodeFluentContext context) : base(context)
{
}
public override string ConnectionString
{
get
{
return GetCurrentTenantConnectionString();
}
set
{
base.ConnectionString = value;
}
}
private string GetCurrentTenantConnectionString()
{
// TODO Implement your own logic
return $"Server=sample;Database=sample_{Context.User.UserName};Trusted_Connection=True;";
}
}
Then you need to register the MultiTenantPersistence
in the configuration file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="Samples" type="CodeFluent.Runtime.CodeFluentConfigurationSectionHandler, CodeFluent.Runtime" />
</configSections>
<Samples persistenceHookTypeName="Sample.MultiTenantPersistence, Sample" />
</configuration>