public static void Start(string[] args) { var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.Development.json") .Build(); Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .Enrich.FromLogContext() .CreateLogger(); NHibernateLogger.SetLoggersFactory(new NHibernate.Logging.Serilog.SerilogLoggerFactory()); try { Log.Information("Starting up"); CreateHostBuilder(args).Build().Run(); // Host.CreateDefaultBuilder().Run<Startup>(); } catch (System.Exception ex) { Log.Fatal(ex, "Application start-up failed"); } finally { Log.CloseAndFlush(); } }
private void InitNHibernate() { var mapper = new ModelMapper(); mapper.AddMappings(typeof(ProductoMap).Assembly.ExportedTypes); HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); string connectionString = _appConfiguration.GetConnectionString("DefaultConnection"); var configuration = new NHibernate.Cfg.Configuration(); configuration.DataBaseIntegration(c => { c.Dialect <NHibernate.Dialect.MySQLDialect>(); c.ConnectionString = connectionString; //c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; //c.SchemaAction = SchemaAutoAction.Validate; #if (DEBUG) c.LogFormattedSql = true; c.LogSqlInConsole = true; #endif }); configuration.AddMapping(domainMapping); var sessionFactory = configuration.BuildSessionFactory(); this.DbSession = sessionFactory.OpenSession(); #if (DEBUG) NHibernateLogger.SetLoggersFactory(new NHLoggerFactory(this.Log)); #endif }
public void WhenConfiguredAsNullThenNoLoggingFactoryIsUsed() { NHibernateLogger.SetLoggersFactory(default(INHibernateLoggerFactory)); // NoLoggingNHibernateLogger is internal Assert.That(NHibernateLogger.For("pizza").GetType().Name, Is.EqualTo("NoLoggingNHibernateLogger")); }
public static void UseAsHibernateLoggerFactory( this Microsoft.Extensions.Logging.ILoggerFactory loggerFactory ) { NHibernateLogger.SetLoggersFactory( new NetCoreLoggerFactory(loggerFactory) ); }
/// <summary> /// 设置 NHiberernate 使用 <see cref="SerilogLoggerFactory"/>; /// 使用 hibernate.cfg.xml 配置 NHibernate; /// 从容器解析 <see cref="XModelMapper"/> 添加到 <see cref="Configuration"/>; /// 根据选项添加 <see cref="CheckTransactionListener"/>; /// 向容器注册 <see cref="Configuration"/>; /// 向容器注册添加了 <see cref="AuditInterceptor"/> 的 <see cref="ISessionFactory"/>; /// 向容器注册 <see cref="ISession"/>; /// 在调用之前,应使用 <see cref="AddModelMapper{TModelMapper}(ContainerBuilder)"/> 添加 <see cref="XModelMapper"/>。 /// </summary> /// <param name="builder"></param> /// <param name="options">配置选项。</param> public static void AddNHibernate(this ContainerBuilder builder) { _logger.Information("正在配置 NHibernate"); NHibernateLogger.SetLoggersFactory(new SerilogLoggerFactory()); _logger.Information("使用 LoggerFactory: {loggerFactory}", typeof(SerilogLoggerFactory)); builder.Register(c => { Configuration configuration = new Configuration(); configuration.Configure(); foreach (var mapper in c.Resolve <IEnumerable <XModelMapper> >()) { _logger.Information("从容器解析到 ModelMapper {modelMapperType}", mapper.GetType()); var mappings = mapper.CompileMappingForEachExplicitlyAddedEntity(); foreach (var mapping in mappings) { configuration.AddMapping(mapping); } } // 开始:nh 事件,检查事务,要求必须打开事务 CheckTransactionListener checkTransactionListener = new CheckTransactionListener(); configuration.AppendListeners(ListenerType.PreInsert, new IPreInsertEventListener[] { checkTransactionListener }); configuration.AppendListeners(ListenerType.PreUpdate, new IPreUpdateEventListener[] { checkTransactionListener }); configuration.AppendListeners(ListenerType.PreDelete, new IPreDeleteEventListener[] { checkTransactionListener }); configuration.AppendListeners(ListenerType.PreLoad, new IPreLoadEventListener[] { checkTransactionListener }); // 结束:nh 事件 _logger.Information("向 NHibernate.Cfg.Configuration 添加了事件侦听程序 CheckTransactionListener"); return(configuration); }).SingleInstance(); builder.Register(c => { // 生成 SessionFactory var configuration = c.Resolve <Configuration>(); ISessionFactory sessionFactory = configuration.BuildSessionFactory(); return(sessionFactory); }).SingleInstance().ExternallyOwned(); builder.Register(c => { var principal = c.Resolve <IPrincipal>(); AuditInterceptor interceptor = new AuditInterceptor(principal); return(c.Resolve <ISessionFactory>() .WithOptions() // 添加审计拦截器 .Interceptor(interceptor) .OpenSession()); } ).InstancePerLifetimeScope(); _logger.Information("已配置 NHibernate"); }
private static ISessionFactory BuildSessionFactory(string connectionString) { NHibernateLogger.SetLoggersFactory(new SerilogLoggerFactory()); return(Fluently.Configure() .Database(PostgreSQLConfiguration.Standard.ConnectionString(connectionString)) .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())) .BuildSessionFactory()); }
private ISessionFactory GetNhSessionFactory() { NHibernateLogger.SetLoggersFactory(new NHLoggerFactory(_loggerFactory)); var sessionFactory = Fluently.Configure() .Database( MsSqlConfiguration.MsSql2012.ConnectionString("Server=sqlserver;Database=TestDb;User Id=sa;Password=SApassword123__;MultipleActiveResultSets=True;Application Name=TestQueryExecutor") .UseOuterJoin() .IsolationLevel(System.Data.IsolationLevel.ReadCommitted)) .Mappings(m => m.FluentMappings.Add <Mappings.UserMapping>().Add <Mappings.UserAddressMapping>()) .BuildSessionFactory(); return(sessionFactory); }
protected override void OnTearDown() { if (_defaultLogger != null) { NHibernateLogger.SetLoggersFactory(_defaultLogger); } using (var session = OpenSession()) using (var transaction = session.BeginTransaction()) { session.CreateQuery("delete from EntityChild").ExecuteUpdate(); session.CreateQuery("delete from Entity").ExecuteUpdate(); transaction.Commit(); } }
public void NewLoggerFactoryTimingsForNoLogging(int iteration) { ResetCounts(); NHibernateLogger.SetLoggersFactory((INHibernateLoggerFactory)null); INHibernateLogger logger2 = NHibernateLogger.For(this.GetType()); var stopwatch = Stopwatch.StartNew(); var iterationCount = 10000000; for (int i = 0; i < iterationCount; i++) { logger2.Debug("message"); logger2.Debug("message with parameters {0}, {1}", "string", 5); } stopwatch.Stop(); Console.WriteLine( "{0} wrote {1:N0} characters to log in {2} ms", nameof(NewLoggerFactoryTimingsForDisabledLogging), GetCounts(), stopwatch.ElapsedMilliseconds); }
protected override void OnSetUp() { _defaultLogger = (INHibernateLoggerFactory)_loggerFactoryField.GetValue(null); NHibernateLogger.SetLoggersFactory(new EnumeratingLoggerFactory()); using (var session = OpenSession()) using (var transaction = session.BeginTransaction()) { var e1 = new EntityChild { Name = "Bob" }; session.Save(e1); var e2 = new Entity { Name = "Sally", Children = new HashSet <EntityChild> { e1 } }; session.Save(e2); transaction.Commit(); } }
override protected void Load(ContainerBuilder builder) { NHibernateLogger.SetLoggersFactory(new SerilogLoggerFactory()); builder.Register(context => Fluently.Configure() .Database(PostgreSQLConfiguration.PostgreSQL82.ConnectionString(_connectionString)) .Mappings(map => _mapping(map)) .ExposeConfiguration(cfg => _exposeConfiguration(cfg)) .BuildConfiguration() ).As <Configuration>().SingleInstance(); builder.Register(context => context.Resolve <Configuration>().BuildSessionFactory()) .As <ISessionFactory>() .SingleInstance(); builder.Register(context => context.Resolve <ISessionFactory>().OpenSession()) .As <ISession>() .InstancePerLifetimeScope() .AutoActivate(); }
public static IServiceCollection AddNHibernate(this IServiceCollection services, string connectionString) { // set serilog as default logger for nhibernate NHibernateLogger.SetLoggersFactory(new NHibernate.Logging.Serilog.SerilogLoggerFactory()); // standard config for nhibernate(could have been done in appsettings.json var mapper = new ModelMapper(); mapper.AddMappings(typeof(NHibernateExtensions).Assembly.ExportedTypes); HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); var configuration = new Configuration(); configuration.DataBaseIntegration(c => { c.Dialect <MsSql2012Dialect>(); c.ConnectionString = connectionString; c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; //c.SchemaAction = SchemaAutoAction.Validate; c.LogFormattedSql = true; c.LogSqlInConsole = true; }); configuration.AddMapping(domainMapping); var sessionFactory = configuration.BuildSessionFactory(); // recreate db each time SchemaExport se = new SchemaExport(configuration); se.Drop(true, true); se.Create(true, true); services.AddSingleton(sessionFactory); services.AddScoped(factory => sessionFactory.OpenSession()); return(services); }
public LearnNHSessionFactory(IConfiguration appConfig) { var fluentConfig = Fluently.Configure() .Database(PostgreSQLConfiguration.Standard .DefaultSchema(appConfig.GetValue <string>("DatabaseSchema")) .FormatSql() .ShowSql() .ConnectionString(appConfig.GetConnectionString("LearnNH"))) .Mappings(mapper => mapper.FluentMappings.AddFromAssemblyOf <EmployeeFNHMapping>()); var config = fluentConfig.BuildConfiguration(); config.SessionFactory().GenerateStatistics(); NHibernateLogger.SetLoggersFactory(new SerilogNHLoggerFactory()); this.SessionFactory = config.BuildSessionFactory(); #if DEBUG new NHibernate.Tool.hbm2ddl.SchemaExport(config) .SetOutputFile(@".\pg_ddl.sql") .Create(false, false); #endif }
public static ISessionFactory Create(DbConfigurations dbConfigurations) { NHibernateLogger.SetLoggersFactory(new SerilogLoggerFactory()); if (dbConfigurations.UseNodaTime) { NpgsqlConnection.GlobalTypeMapper.UseNodaTime(); } var dbConfigurations1 = dbConfigurations; var persistenceCfg = PostgreSQLConfiguration.Standard .Provider <global::NHibernate.Connection.DriverConnectionProvider>() .Dialect <PostgreSQL83Dialect>() .Driver <NpgsqlDriverExtended>() .ConnectionString(dbConfigurations1.ConnectionString); if (dbConfigurations.UseNetTopologySuite) { NpgsqlConnection.GlobalTypeMapper.UseRawPostgis(); persistenceCfg.Dialect <global::NHibernate.Spatial.Dialect.PostGis20Dialect>(); } var cfg = Fluently.Configure() .Database(persistenceCfg) .Mappings(x => { dbConfigurations1.EntityTypeAssemblies.ForEach(y => x.FluentMappings.AddFromAssembly(y)); x.FluentMappings.Conventions.Setup(y => y.Add(AutoImport.Never())); if (dbConfigurations.UseNodaTime) { x.FluentMappings.Conventions.Add <NodaTimeConventions>(); } if (dbConfigurations.UseNetTopologySuite) { x.FluentMappings.Conventions.Add <PostGisConventions>(); } x.FluentMappings.Conventions.Add <GeneralConventions>(); x.FluentMappings.Conventions.Add <ListConventions>(); x.FluentMappings.Conventions.Add <RangeConventions>(); x.FluentMappings.Conventions.Add <JsonConventions>(); }) .ExposeConfiguration(x => { if (!string.IsNullOrWhiteSpace(dbConfigurations.SchemaExportFilename)) { new SchemaExport(x).Execute(script => File.AppendAllText(dbConfigurations.SchemaExportFilename, script), false, false); } }) .BuildConfiguration(); if (dbConfigurations.UseNetTopologySuite) { cfg.AddAuxiliaryDatabaseObject(new SpatialAuxiliaryDatabaseObject(cfg)); Metadata.AddMapping(cfg, MetadataClass.GeometryColumn); Metadata.AddMapping(cfg, MetadataClass.SpatialReferenceSystem); } return(cfg.BuildSessionFactory()); }
public void WhenConfiguredAsNullThenNoLoggingFactoryIsUsed_Obsolete() { NHibernateLogger.SetLoggersFactory(default(INHibernateLoggerFactory)); Assert.That(LoggerProvider.LoggerFor("pizza"), Is.InstanceOf <NoLoggingInternalLogger>()); }
protected override void Load(ContainerBuilder builder) { NHibernateLogger.SetLoggersFactory(new NLogLoggerFactory()); builder.RegisterType <AuditEventListener>().SingleInstance(); builder.RegisterAssemblyTypes(AppAssemblies.All) .Where(x => x.Name.EndsWith("Listener") && x.GetInterfaces() .Any(i => i.Namespace.Equals(typeof(IPreUpdateEventListener).Namespace))) .AsSelf() .SingleInstance(); builder.Register(c => { var cfg = CreateConfiguration(c, _connectionString, _isTestEnvironment); if (_recreateDatabase) { logger.Warn("Recreating db schema"); new SchemaExport(cfg).Execute(false, true, false); } return(CreateConfiguration(c, _connectionString, _isTestEnvironment)); }).SingleInstance(); builder.Register(c => { var factory = Policy .Handle <SqlException>() .WaitAndRetry(5, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, retryIn) => logger.Warn(ex, "Error while building session factory ... retrying in {seconds} seconds", retryIn.TotalSeconds)) .Execute(() => c.Resolve <Configuration>() .SetProperty("current_session_context_class", "thread_static") .BuildSessionFactory()); return(factory); }) .As <ISessionFactory>() .SingleInstance(); //builder.Register(c => c.Resolve<ISessionFactory>().OpenSession()).As<ISession>().InstancePerLifetimeScope(); //builder.Register(c => c.Resolve<Lazy<ISession>>().Value).As<ISession>().InstancePerLifetimeScope(); builder.RegisterType <SessionContext>().InstancePerLifetimeScope(); builder.Register(c => { var sessionFactory = c.Resolve <ISessionFactory>(); var ctx = c.Resolve <SessionContext>(); ctx.Put(c.Resolve <ILifetimeScope>()); return(new Lazy <ISession>(() => { var session = sessionFactory.OpenSession(); session.BindContext(ctx); session.BeginTransaction(); return session; })); }).InstancePerLifetimeScope(); builder.Register(c => c.Resolve <Lazy <ISession> >().Value).As <ISession>(); builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerLifetimeScope(); logger.Info("NHibernate components registered"); }
static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .ReadFrom.AppSettings() .CreateLogger(); NHibernateLogger.SetLoggersFactory(new SerilogLoggerFactory()); NHibernateHelper nhibernateHelper = null; try { var databaseType = ConfigurationManager.AppSettings["database_type"]; if (string.IsNullOrEmpty(databaseType)) { databaseType = "sql"; } else { databaseType = databaseType.ToLowerInvariant(); } var connectionString = ConfigurationManager.ConnectionStrings[databaseType] .ConnectionString; if (string.IsNullOrWhiteSpace(connectionString)) { throw new ConfigurationErrorsException( "connection string can't be null"); } if (databaseType == "sql") { nhibernateHelper = new NHibernateHelperSQL(connectionString); } else if (databaseType == "oracle") { nhibernateHelper = new NHibernateHelperOracle(connectionString); } else { throw new ConfigurationErrorsException( "databaseType must be either 'sql' or 'oracle'-case insensitive"); } nhibernateHelper.GetSessionFactory(); SeedData.Initialize(nhibernateHelper); var nhibernateRunner = new NHibernate(nhibernateHelper); nhibernateRunner.Run(); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if (nhibernateHelper != null) { nhibernateHelper.CloseSessionFactory(); } } }
public static void Initialize() { NHibernateLogger.SetLoggersFactory(new NHibernateProfilerLoggerFactory()); }
public static ILoggerFactory UseAsNHibernateLoggerProvider(this ILoggerFactory factory) { NHibernateLogger.SetLoggersFactory(new MicrosoftLoggerFactory(factory)); return(factory); }
public RCommonSessionFactory(ISessionFactory sessionFactory, INHibernateLoggerFactory loggerFactory) { NHibernateLogger.SetLoggersFactory(loggerFactory); this._sessionFactory = sessionFactory; }