I faced problem in my application: I have two databases and I want to access both with NHibernate, but in the configration file I have only one connection string for one database. So how can I pass more than one connection string to NHibernate?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
I usually define connection strings in my app.config
:
<connectionStrings>
<add name="connection1" connectionString="Data Source=;User ID=;Password=;" />
<add name="connection2" connectionString="Data Source=;User ID=;Password=;" />
</connectionStrings>
then I create 2 separate (nhibernate) config files with nhibernate configurations (in case you have 2 different databases).
I use one class which allows me to create a session factory:
public class NHibernateSessionFactory
{
private ISessionFactory sessionFactory;
private readonly string ConnectionString = "";
private readonly string nHibernateConfigFile = "";
public NHibernateSessionFactory(String connectionString, string nHConfigFile)
{
this.ConnectionString = connectionString;
this.nHibernateConfigFile = nHConfigFile;
}
public ISessionFactory SessionFactory
{
get { return sessionFactory ?? (sessionFactory = CreateSessionFactory()); }
}
private ISessionFactory CreateSessionFactory()
{
Configuration cfg;
cfg = new Configuration().Configure(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, this.nHibernateConfigFile));
// With this row below Nhibernate searches for the connection string inside the App.Config.
// cfg.SetProperty(NHibernate.Cfg.Environment.ConnectionStringName, System.Environment.MachineName);
cfg.SetProperty(NHibernate.Cfg.Environment.ConnectionString, this.ConnectionString);
#if DEBUG
cfg.SetProperty(NHibernate.Cfg.Environment.GenerateStatistics, "true");
cfg.SetProperty(NHibernate.Cfg.Environment.ShowSql, "true");
#endif
return (cfg.BuildSessionFactory());
}
}
Now I can create many different session factories with their own specific configuration:
var sessionFactory1 = new NHibernateSessionFactory("connection string 1", "sql.nhibernate").SessionFactory;
var sessionFactory2 = new NHibernateSessionFactory("connection string 2", "ora.nhibernate").SessionFactory;
You can find more info here.
回答2:
For each Database, you need a own SessionFactory. If you omit the ConnectionString in your NH config, you can specify it in Code while building your Sessionfactory:
var sessionFactory1 = new Configuration()
.Configure()
.SetProperty("connection.connection_string", "First Connection String").BuildSessionFactory();
var sessionFactory2 = new Configuration()
.Configure()
.SetProperty("connection.connection_string", "Second Connection String").BuildSessionFactory();