narsil/Tanshu.Accounts.Repository/SetupStore.cs

128 lines
4.0 KiB
C#

using System;
using NHibernate;
using NHibernate.Cfg;
using Tanshu.Accounts.Entities;
using NHibernate.Mapping.ByCode;
using System.Reflection;
using NHibernate.Tool.hbm2ddl;
using NHibernate.Cfg.MappingSchema;
using System.Data;
using Tanshu.Accounts.Entities.Auth;
namespace Tanshu.Accounts.Repository
{
public sealed class SessionManager
{
private readonly Configuration cfg;
private readonly ISessionFactory factory;
private static SessionManager instance;
private SessionManager(bool forTesting)
{
cfg = ConfigureNHibernate(forTesting);
factory = cfg.BuildSessionFactory();
}
public static void Initialize(bool forTesting)
{
if (instance == null)
{
instance = new SessionManager(forTesting);
}
}
public static ISession Session
{
get
{
if (instance == null)
throw new ApplicationException("Session factory not initalized. Cannot get Session");
return instance.GetSession();
}
}
public static IStatelessSession StatelessSession
{
get
{
if (instance == null)
throw new ApplicationException("Session factory not initalized. Cannot get Session");
return instance.GetStatelessSession();
}
}
private Configuration ConfigureNHibernate(bool forTesting)
{
var configure = new Configuration();
configure.SessionFactoryName("BuildIt");
configure.DataBaseIntegration(db =>
{
db.Dialect<NHibernate.Dialect.MsSql2005Dialect>();
db.Driver<NHibernate.Driver.SqlClientDriver>();
db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
db.IsolationLevel = IsolationLevel.ReadCommitted;
db.ConnectionStringName = "Con";
db.Timeout = 10;
if (forTesting)
{
// enabled for testing
db.LogFormattedSql = true;
db.LogSqlInConsole = true;
db.AutoCommentSql = true;
}
});
var mapping = GetMappings();
configure.AddDeserializedMapping(mapping, "NHSchemaTest");
//SchemaMetadataUpdater.QuoteTableAndColumns(configure);
configure.SetInterceptor(new VoucherDirty());
var timeout = TimeSpan.FromMinutes(10).TotalSeconds;
configure.SetProperty("command_timeout", timeout.ToString());
return configure;
}
private static HbmMapping GetMappings()
{
var mapper = new ModelMapper();
var entities = new Type[] {
typeof(VoucherMap),
typeof(UserMap),
typeof(CustomerMap),
typeof(UserGroupMap),
typeof(KotMap),
typeof(ReprintMap),
typeof(InventoryMap),
typeof(InventoryModifierMap),
typeof(GroupMap),
typeof(RoleGroupMap),
typeof(ProductMap),
typeof(ModifierMap),
typeof(ProductGroupModifierMap),
typeof(RoleMap),
typeof(ProductGroupMap),
typeof(PrintLocationMap),
typeof(TaxMap),
typeof(VoucherSettlementMap),
typeof(FoodTableMap),
typeof(MachineLocationMap),
typeof(SettingMap)
};
mapper.AddMappings(entities);
var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
return mapping;
}
private ISession GetSession()
{
return factory.OpenSession();
}
private IStatelessSession GetStatelessSession()
{
return factory.OpenStatelessSession();
}
}
}