コード例 #1
0
        /// <summary>
        /// Creates session factory
        /// </summary>
        /// <param name="configurationReader">configuration reader</param>
        /// <returns></returns>
        private static ISessionFactory CreateSessionFactory(IConfigurationReader configurationReader)
        {
            var configuration = new NHibernate.Cfg.Configuration();
            configuration.SessionFactoryName("Jumblocks Blog");

            configuration.DataBaseIntegration(db =>
            {
                db.Dialect<MsSql2008FixedDialect>();
                db.IsolationLevel = IsolationLevel.ReadCommitted;
                db.ConnectionString = configurationReader.ConnectionStrings["BlogDb"].ConnectionString;
                db.BatchSize = 100;

                //for testing
                db.LogFormattedSql = true;
                db.LogSqlInConsole = true;
                db.AutoCommentSql = true;
            });

            var mapper = new ModelMapper();
            mapper.AddMapping<BlogPostMap>();
            mapper.AddMapping<BlogUserMap>();
            mapper.AddMapping<ImageReferenceMap>();
            mapper.AddMapping<TagMap>();
            mapper.AddMapping<SeriesMap>();

            mapper.AddMapping<UserMap>();
            mapper.AddMapping<RoleMap>();
            mapper.AddMapping<OperationMap>();

            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            configuration.CurrentSessionContext<WebSessionContext>();

            return configuration.BuildSessionFactory();
        }
コード例 #2
0
		public virtual void Apply(Configuration configuration, IDatabaseProvider databaseProvider)
		{
			configuration.CurrentSessionContext<CallSessionContext>();

			configuration.DataBaseIntegration(db => SetDatabase(db, databaseProvider, configuration));

			configuration.Cache(SetCache);

			configuration.Proxy(SetProxy);
		}
コード例 #3
0
        public static void Initialize()
        {
            if (SessionFactoryHolder.DefaultSessionFactory != null) { return; }

            var cfg = new Configuration();
            cfg.CurrentSessionContext<WcfOperationSessionContext>()
               .DataBaseIntegration(ForSQLiteInMemory)
               .Proxy(p => p.ProxyFactoryFactory<ProxyFactoryFactory>())
               .SessionFactory()
                    .GenerateStatistics();

            SessionFactoryHolder.DefaultSessionFactory = cfg.BuildSessionFactory();
        }
コード例 #4
0
 public static ISessionFactory GetNHibernateSessionFactory()
 {
     var configure = new NHibernate.Cfg.Configuration();
     configure.DataBaseIntegration(delegate(NHibernate.Cfg.Loquacious.IDbIntegrationConfigurationProperties dbi) {
         dbi.ConnectionStringName = "mvcWithNHibernate";
         dbi.Dialect<NHibernate.Dialect.MySQLDialect>();
         dbi.Driver<NHibernate.Driver.MySqlDataDriver>();
         dbi.Timeout = 255;
     });
     configure.CurrentSessionContext<NHibernate.Context.WebSessionContext>();
     //configure.AddAssembly(typeof(NHibernateMappings.User).Assembly);
     configure.AddAssembly(typeof(NHibernateMappings.Shop).Assembly);
     return configure.BuildSessionFactory();
 }
コード例 #5
0
        public static Configuration GetDefaultNHConfiguration(bool autoMapAll = false)
        {
            var cfg = new Configuration();

            cfg
            .CurrentSessionContext <ThreadStaticSessionContext>()
            .DataBaseIntegration(x => {
                x.FullDriver(ConfigurationManager.AppSettings["nhibernate.dbdriver"] ?? "mssql2012");
                x.ConnectionStringName = "acrframework";
            });

            if (autoMapAll)
            {
                cfg.AddAssemblyByCodeMap <AcrModelMapper>(Assembly.GetExecutingAssembly());
            }
            return(cfg);
        }
コード例 #6
0
        public static ISessionFactory GetNhibernateSessionFactory()
        {
            var configure = new NHibernate.Cfg.Configuration();

            configure.DataBaseIntegration(delegate(NHibernate.Cfg.Loquacious.IDbIntegrationConfigurationProperties dbi) {
                dbi.ConnectionString = "mvcWithNHibernate";
                dbi.Dialect <NHibernate.Dialect.MsSql2012Dialect>();
                dbi.Driver <NHibernate.Driver.SqlClientDriver>();
                dbi.Timeout = 255;
            });

            configure.AddAssembly(typeof(Address).Assembly);

            configure.CurrentSessionContext <WebSessionContext>();

            return(configure.BuildSessionFactory());
        }
コード例 #7
0
        protected virtual void RegisterProperties(NHibernate.Cfg.Configuration configuration)
        {
            configuration.Proxy(p => p.ProxyFactoryFactory <ComponentProxyFactoryFactory>());
            configuration.DataBaseIntegration(db =>
            {
                db.Dialect <MsSql2005Dialect>();
                db.Driver <SqlClientDriver>();
                //db.ConnectionStringName = "ConnectionString";
                db.ConnectionString = Common.Constants.AppConfig.ConnectionString;
                db.BatchSize        = 10;
            });
            configuration.CurrentSessionContext <ThreadLocalConversationalSessionContext>();

            configuration.Cache(cp =>
            {
                cp.UseQueryCache = true;
                cp.Provider <SysCacheProvider>();
            });
        }
コード例 #8
0
        private void CreateSessionFactory(string assemblyName, string connStr)
        {
            Configuration cfg = new Configuration();
            cfg.CurrentSessionContext<ThreadStaticSessionContext>();
            cfg.DataBaseIntegration(o =>
                {
                    o.ConnectionProvider<DriverConnectionProvider>();
                    o.Dialect<SQLiteDialect>();
                    o.Driver<SQLite20Driver>();
                    o.ConnectionString = connStr;
                    o.BatchSize = 100;
                });
            cfg.AddAssembly(assemblyName);

            SessionFactory = cfg.BuildSessionFactory();

            SchemaExport = new SchemaExport(cfg);
            SchemaExport.Create(false, true);
        }
コード例 #9
0
ファイル: NHibernateConfig.cs プロジェクト: sunpa/SampleTodo
        /// <summary>
        /// Starts this instance.
        /// </summary>
        public static void Start()
        {
            var configuration = new Configuration();
            configuration.DataBaseIntegration(db =>
            {
                db.Dialect<MsSql2012Dialect>();
                db.Driver<SqlClientDriver>();
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                db.IsolationLevel = IsolationLevel.ReadCommitted;
                db.SchemaAction = SchemaAutoAction.Validate;
                db.ConnectionStringName = ConnectionStringName;
            });

            configuration.CurrentSessionContext<WebSessionContext>();
            var factory = Fluently.Configure(configuration)
                .Mappings(m => m.FluentMappings.AddFromAssembly(typeof(TodoMap).Assembly))
                .ExposeConfiguration(cfg => new SchemaExport(cfg).Execute(false, true, false))
                .BuildSessionFactory();

            SessionSource.SetFactory(factory);
        }
コード例 #10
0
        protected SessionFactoryProvider(IConfiguration configuration, string nick, IInterceptor interceptor)
        {
            connectionInfo = configuration.GetSection("db")
                             .Get <ConnectionInfo[]>()
                             .SingleOrDefault(ci => ci.Nick == nick && ci.DbServerType == ServerType);
            if (connectionInfo == null)
            {
                throw new InvalidOperationException($"Connection with name {nick} is not found");
            }

            nhConfig = new NhConfiguration();
            nhConfig.CurrentSessionContext <ThreadLocalSessionContext>();
            nhConfig.SetProperty(Environment.SessionFactoryName, nick);
            nhConfig.Interceptor = interceptor ?? new EmptyInterceptor();
            nhConfig.SetProperty(Environment.UseSecondLevelCache, "false");
            Logger.LogDebug("NHibernate configuration: " + $"DbNick: {nhConfig.GetProperty(Environment.SessionFactoryName)}, "
                            + $"UseSecondLevelCache: {nhConfig.GetProperty(Environment.UseSecondLevelCache)}, "
                            + $"CacheDefaultExpiration: {nhConfig.GetProperty(Environment.CacheDefaultExpiration)}");

            Nick = nick;
            IsSkipHealthCheckEntity = connectionInfo.IsSkipHealthCheckEntity;
        }
コード例 #11
0
        public static ISessionFactory GetNHibernateSessionFactory(string connStringKeyName)
        {
            if (string.IsNullOrEmpty(connStringKeyName))
                throw new ArgumentNullException("connStringKeyName");

            var configs = new NHibernate.Cfg.Configuration();

            configs.DataBaseIntegration(i =>
            {
                i.Dialect<NHibernate.Dialect.MsSql2012Dialect>();
                i.Driver<NHibernate.Driver.Sql2008ClientDriver>();
                i.ConnectionStringName = connStringKeyName;
                i.ConnectionProvider<NHibernate.Connection.DriverConnectionProvider>();
            });

            configs.CurrentSessionContext<NHibernate.Context.WebSessionContext>();

            // assembly of poco classes
            configs.AddAssembly(typeof(NHibernateMVCApp.Repository.Mappings.Product).Assembly);

            return configs.BuildSessionFactory();
        }
コード例 #12
0
ファイル: NHibernateRegistry.cs プロジェクト: syurov/rt.srz
        /// <summary>
        ///   Initializes a new instance of the <see cref="NHibernateRegistry" /> class.
        ///   Конструктор
        /// </summary>
        public NHibernateRegistry()
        {
            var configuration = new Configuration();

            configuration.Configure();
            var defaultConnectionString = ConfigurationManager.ConnectionStrings["default"];

            configuration.SetProperty(Environment.ConnectionString, defaultConnectionString.ConnectionString);
            configuration.CurrentSessionContext <SmartSessionContext>();
            var sessionFactory = configuration.BuildSessionFactory();

            ForSingletonOf <ISessionFactory>().Use(sessionFactory);

            var manager = new ManagerSessionFactorys();

            manager.SetDefaultFactory(sessionFactory);
            if (ConfigManager.PoolNhibernateSection != null)
            {
                foreach (var file in ConfigManager.PoolNhibernateSection.FileNameConfigaration.Cast <FileNameElement>())
                {
                    configuration = new Configuration();
                    var filename = file.FileNameConfiguration;
                    if (!File.Exists(file.FileNameConfiguration))
                    {
                        filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, file.FileNameConfiguration);
                    }

                    configuration.Configure(filename);
                    var connectionString = ConfigurationManager.ConnectionStrings[file.FileNameConfiguration];
                    configuration.SetProperty(Environment.ConnectionString, connectionString.ConnectionString);
                    configuration.CurrentSessionContext <SmartSessionContext>();
                    sessionFactory = configuration.BuildSessionFactory();
                    manager.AddSessionFactory(file.FileNameConfiguration, sessionFactory);
                }
            }

            ForSingletonOf <IManagerSessionFactorys>().Use(manager);
        }
コード例 #13
0
        public static ISessionFactory ReturnSessionFactory()
        {
            ISessionFactory SF     = null;
            var             config = new NHibernate.Cfg.Configuration();

            try
            {
                config.DataBaseIntegration(delegate(NHibernate.Cfg.Loquacious.IDbIntegrationConfigurationProperties cfgbbi)
                {
                    cfgbbi.ConnectionStringName = "ConnectionMysql";
                    cfgbbi.Driver <NHibernate.Driver.MySqlDataDriver>();
                    cfgbbi.Dialect <NHibernate.Dialect.MySQL55Dialect>();
                    cfgbbi.Timeout = 120;
                });
                config.CurrentSessionContext <WebSessionContext>();

                config.AddAssembly(typeof(TblAdmin).Assembly);
                SF = config.BuildSessionFactory();
            }
            catch (Exception ex)
            { }
            return(SF);
        }
        public static Configuration Initialize()
        {
            ModelMapper mapper = new ModelMapper();

            mapper.AddMappings(Assembly.GetAssembly(typeof(NHibernateSessionManager)).GetExportedTypes());

            Configuration cfg = new Configuration();

            cfg.DataBaseIntegration(c =>
            {
                c.Driver<SqlServerCeDriver>();
                c.Dialect<MsSqlCe40Dialect>();

                c.LogSqlInConsole = true;
                c.LogFormattedSql = true;

                c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                c.ConnectionString   = ConnectionString;
            });
            cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            cfg.CurrentSessionContext<ThreadStaticSessionContext>();

            // Set up second level caching
            cfg.Cache(props =>
            {
                props.Provider<AppFabricProvider>();
                props.UseQueryCache = true;
            });

            // (Re-)create the database.
            new SchemaExport(cfg).Execute(false, true, false);

            _sessionFactory = cfg.BuildSessionFactory();

            return cfg;
        }
コード例 #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(option => option.EnableEndpointRouting = false);
            var mvcBuilder = services.AddMvc();

            services.AddControllers().AddNewtonsoftJson();
            services.AddControllers().AddNewtonsoftJson(opt => {
                var ss       = JsonSerializationFns.UpdateWithDefaults(opt.SerializerSettings);
                var resolver = ss.ContractResolver;
                if (resolver != null)
                {
                    var res            = resolver as DefaultContractResolver;
                    res.NamingStrategy = null; // <<!-- this removes the camelcasing
                }

#if NHIBERNATE
                // NHibernate settings
                var settings = opt.SerializerSettings;
                settings.ContractResolver = NHibernateContractResolver.Instance;

                settings.Error = delegate(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args) {
                    // When the NHibernate session is closed, NH proxies throw LazyInitializationException when
                    // the serializer tries to access them.  We want to ignore those exceptions.
                    var error = args.ErrorContext.Error;
                    if (error is NHibernate.LazyInitializationException || error is System.ObjectDisposedException)
                    {
                        args.ErrorContext.Handled = true;
                    }
                };

                if (!settings.Converters.Any(c => c is NHibernateProxyJsonConverter))
                {
                    settings.Converters.Add(new NHibernateProxyJsonConverter());
                }
#endif
            });


            mvcBuilder.AddMvcOptions(o => { o.Filters.Add(new GlobalExceptionFilter()); });

            var tmp = Configuration.GetConnectionString("NorthwindIB_CF");
#if EFCORE
            services.AddDbContext <NorthwindIBContext_CF>(options => options.UseSqlServer(tmp));
#endif

#if NHIBERNATE
            services.AddSingleton <NHibernate.ISessionFactory>(factory => {
                var cfg = new NHibernate.Cfg.Configuration();
                cfg.DataBaseIntegration(db => {
                    db.ConnectionString = tmp;
                    db.Dialect <MsSql2008Dialect>();
                    db.Driver <Sql2008ClientDriver>();
                    db.LogFormattedSql = true;
                    db.LogSqlInConsole = true;
                });
                cfg.Properties.Add(Environment.DefaultBatchFetchSize, "32");
                cfg.CurrentSessionContext <NHibernate.Context.ThreadStaticSessionContext>();
                var modelAssembly = typeof(Models.NorthwindIB.NH.Customer).Assembly;
                cfg.AddAssembly(modelAssembly); // mapping is in this assembly

                var sessionFactory = cfg.BuildSessionFactory();
                return(sessionFactory);
            });
#endif
        }
コード例 #16
0
 public static void Configure()
 {
     NHConguration = new Configuration().Configure();
     NHConguration.CurrentSessionContext<WcfOperationSessionContext>();
     NHConguration.LinqToHqlGeneratorsRegistry<NHibernateLinqToHqlGeneratorsRegistry>();
     sessionFactory = NHConguration.BuildSessionFactory();
 }
コード例 #17
0
 protected override void ExposeConfiguration(Configuration cfg)
 {
     base.ExposeConfiguration(cfg);
     cfg.CurrentSessionContext<NHibernate.Context.WebSessionContext>();
 }