private static ISessionFactory sessionFactory;
private ISession session;
public ISession GetSession()
{
Initialize();
if (session == null)
session = sessionFactory.OpenSession();
return session;
}
public void CloseSession()
{
if (session.IsNull())
return;
session.Close();
session.Dispose();
session = null;
}
private static void Initialize()
{
if (sessionFactory.IsNull())
sessionFactory = GetProjectNHibernateConfiguraton().BuildSessionFactory();
}
private static FluentConfiguration GetProjectNHibernateConfiguraton()
{
var nhibernateConfiguration = new Configuration().Configure();
var model = AutoMap.AssemblyOf<Entity>().IgnoreBase<Entity>()
.Where(type => typeof (Entity).IsAssignableFrom(type))
.Conventions.AddFromAssemblyOf<Entity>()
.UseOverridesFromAssemblyOf<Entity>();
return Fluently.Configure(nhibernateConfiguration)
.Mappings(mappingConfiguration => mappingConfiguration.AutoMappings.Add(model));
}
#region Manually used to generate DB schema SQL scripts
internal static string DROP_SCHEMA_SQL_SCRIPT_NAME =
new FileInfo(Path.Combine(Path.GetTempPath(), "Schema_Drop.sql")).FullName;
internal static string CREATE_SCHEMA_SQL_SCRIPT_NAME =
new FileInfo(Path.Combine(Path.GetTempPath(), "Schema_Create.sql")).FullName;
/// <summary>Use TestDriven.Net to run this method as a test to generate SQL scripts and their files.</summary>
internal static void Generate_Database_Schema_and_Create_SQL_script_files()
{
GetProjectNHibernateConfiguraton()
.ExposeConfiguration(SchemaGenerator)
.BuildSessionFactory();
}
private static void SchemaGenerator(Configuration configuration)
{
var schemaExport = new SchemaExport(configuration);
schemaExport.SetOutputFile(DROP_SCHEMA_SQL_SCRIPT_NAME).Drop(true, false);
schemaExport.SetOutputFile(CREATE_SCHEMA_SQL_SCRIPT_NAME).Create(true, false);
}
#endregion