基本上我使用NHibernate连接到.NET上的WinForm项目应用程序的数据库。
但是,每个项目都需要连接不同的数据库。我如何使用多个DBProvider连接或多个将映射到我想要的实体的ISessionFactories进行配置?
这是我的代码示例:
我的ISession和ISessionFactory的基本基类:
public abstract class clsNHibernateBase
{
private ISessionFactory sessionFactory;
public ISessionFactory SessionFactory
{
protected get
{
return sessionFactory;
}
set
{
sessionFactory = value;
}
}
public ISession GetCurrentSession
{
get
{
return sessionFactory.GetCurrentSession();
}
}
public ISession GetOpenSession
{
get
{
return sessionFactory.OpenSession();
}
}
我还有一个在我的infra.xml上链接的类,它设置了我的IDbProvider
public class clsCustomDbProviderFactoryObject
{
public static IDbProvider GetDbProvider()
{
string providerName = System.Configuration.ConfigurationManager.AppSettings["DbProviderFactory"];
string connectionString = clsCustomConnectionStringProvider.GetConnectionString();
IDbProvider dbProvider = DbProviderFactory.GetDbProvider(providerName);
dbProvider.ConnectionString = connectionString;
return dbProvider;
}
}
在我的infra.xml上,我为我的IDbProvider声明了我的类:
<object id="DbProvider" type="Spring.Objects.Factory.Config.MethodInvokingFactoryObject, Spring.Core">
<property name="TargetType" value="Dao.clsCustomDbProviderFactoryObject, Base.Infra"/>
<property name="TargetMethod" value="GetDbProvider"/>
以下是覆盖NewSessionFactory以进行映射和配置的类:
public class clsCustomLocalSessionFactoryObject : LocalSessionFactoryObject
{
protected override NHibernate.ISessionFactory NewSessionFactory(NHibernate.Cfg.Configuration config)
{
try
{
var mappings = GetMappings();
config.AddDeserializedMapping(mappings, null);
config.Configure();
config.BuildSessionFactory();
}
catch (Exception ex)
{
throw ex;
}
return base.NewSessionFactory(config);
}
}
我的架构的示例映射:
public class entRoleMap : ClassMapping<entRole>
{
public entRoleMap()
{
Table("Roles");
Schema("schema");
Lazy(false);
Mutable(false);
Id(x => x.intRoleID, map =>
{
map.Column("RoleID");
map.Generator(Generators.Native);
});
Property(x => x.strRoleName, map => map.Column("Rolename"));
Property(x => x.blIsActive, map => map.Column("isActive"));
}
}
所有这些代码只指向一个连接字符串或一个数据库。我想配置它,以便它可以处理多个sessionfactories或在运行时更改我的数据库连接,因为我使用WinForm而不是Web应用程序。