假設所有的數據庫都具有相同的模式,您可以使用自定義的DriverConnectionProvider動態地切換連接。在下面的代碼中,我將web.config中的連接字符串加載到字典中,然後使用URL中的「租戶」路由值檢索它們。
public class TenantConnectionProvider : DriverConnectionProvider
{
private IDictionary<string, string> _tenantConnectionStrings;
public override void Configure(IDictionary<string, string> settings)
{
// Load connection strings from config file
_tenantConnectionStrings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (ConnectionStringSettings connectionStringSetting in ConfigurationManager.ConnectionStrings)
{
_tenantConnectionStrings.Add(connectionStringSetting.Name, connectionStringSetting.ConnectionString);
}
base.Configure(settings);
}
public override IDbConnection GetConnection()
{
var connectionString = GetConnectionString(); //not shown, mine is for Web API
var connection = new SqlConnection(connectionString);
connection.Open();
return connection;
}
}
我再配置此使用功能NHibernate:
// connection string has to be set even though custom provider is used
var config = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString("custom").Provider<TenantConnectionProvider>)
.Mappings(m =>
{
m.FluentMappings.AddFromAssemblyOf<MyClass>();
});
感謝您的迴應。但我想ISession注入到DAO對象。現在IOC如何知道在運行時注入哪個ISession? – user3329192
假設你使用session-per-request,只有一個ISession。會話工廠將在每次創建會話時使用自定義DriverConnectionProvider提供的連接提供會話。依賴注入框架只需要注入ISession,沒有別的。 –