Hi there,
i got some fundamental questions. An ISessionFactory is expensive to use, so there should be only one for each Database used. In my cases there is just one Database and so i implemented an Singleton-Pattern for this case. Do i need this or is nHibernate managing only one Factory for each Database internally?
Furthermore I´ve read that Sessions are quiet cheap and so i should use a session-per-request. On the other hand i´ve read in that
http://www.theserverside.net/articles/s ... ibernateP2 :"Sessions are also expensive to create (though not nearly as expensive as SessionFactories)."
So should i use a session-per-operation and just disconnect the session in each method?
Finally here is my test-code for singleton and session-per-request. Any comments on this are welcome, cause i am not sure if i did the singleton right.
Code:
/// <summary>
/// Singleton-Pattern for ISession and doing some configuration
/// </summary>
public class Configure
{
private Configuration cfg = null;
private ISessionFactory sessions = null;
static readonly Configure instance = new Configure();
static Configure(){}
Configure()
{
this.cfg = new Configuration()
.AddAssembly("NHTest");
this.sessions = cfg.BuildSessionFactory();
}
public static Configure Instance
{
get
{
return instance;
}
}
public ISessionFactory Sessions
{
get
{
return sessions;
}
}
public Configuration Cfg
{
get
{
return cfg;
}
}
public void ErschaffeTabellen(Configuration cfg)
{
Console.WriteLine("###### Erstelle Datenbank-Schema! Verwerfe Tabellen und erstelle Neue! #######");
Console.WriteLine("##############################################################################\n");
NHibernate.Tool.hbm2ddl.SchemaExport schemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);
schemaExport.SetOutputFile("schema.txt");
schemaExport.Create(true, true);
}
}
class Class1
{
/// <summary>
/// Do some Testing
/// </summary>
/// <param name="args"></param>
[STAThread]
static void Main(string[] args)
{
Configure config = Configure.Instance;
ISessionFactory fabrik = config.Sessions;
ISession session = fabrik.OpenSession();
config.ErschaffeTabellen(config.Cfg);
FillDB(fabrik);
//...
}
public static void FillDB(ISessionFactory fabrik)
{
NHibernate.ISession session = null;
NHibernate.ITransaction transaction = null;
//...
// Objects are created here!!!
//...
Random rd = new Random();
try
{
session = fabrik.OpenSession();
transaction = session.BeginTransaction();
for (int i = 0; i < 200; i++)
{
// creating 200 objects
session.Save(newObject);
}
// Commit modifications (=> Build and execute queries)
transaction.Commit();
}
catch
{
if(transaction != null)
transaction.Rollback(); // Error => we MUST roll back modifications
throw; // Here, we throw the same exception so that it is handled (printed)
}
finally
{
if(session != null)
session.Close();
}
}
}
Regards,
Chris