Пример #1
0
        /// <summary>
        /// Adds T mapping to <param name="configuration">Configuration</param>.
        /// </summary>
        /// <typeparam name="T">The mapping class.</typeparam>
        /// <param name="configuration">The existing <see cref="Configuration"/>.</param>
        public static void AddMappings <T>(Configuration configuration) where T : IConformistHoldersProvider, new()
        {
            var mapper = new ModelMapper();

            mapper.AddMapping <T>();
            var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities();

            configuration.AddMapping(mappings);
        }
Пример #2
0
        private Configuration AddConfiguration(
            string factoryKey,
            string[] mappingAssemblies,
            IEnumerable <EventListener> eventListeners,
            global::NHibernate.Cfg.Configuration cfg)
        {
            var sessionFactory = this.CreateSessionFactoryFor(mappingAssemblies, eventListeners, cfg);

            return(this.AddConfiguration(factoryKey, sessionFactory, cfg));
        }
Пример #3
0
        private static Configuration CreateNHibernateConfiguration()
        {
            var configuration = new Configuration();
            var hc            = ConfigurationManager.GetSection(CfgXmlHelper.CfgSectionName) as IHibernateConfiguration;

            if (hc != null && hc.SessionFactory != null)
            {
                configuration = configuration.Configure();
            }
            else if (File.Exists(GetDefaultConfigurationFilePath()))
            {
                configuration = configuration.Configure();
            }
            return(configuration);
        }
Пример #4
0
 public NHibernateConfigurationBuilder(ReadOnlySettings settings, string connectionStringKeySuffix, params string[] settingsKeys)
 {
     configuration = settingsKeys.Select(settings.GetOrDefault <Configuration>).FirstOrDefault(x => x != null);
     if (configuration == null)
     {
         var configurationProperties = InitFromConfiguration(settings);
         var overriddenProperties    = OverrideConnectionStringSettingIfNotNull(configurationProperties, connectionStringKeySuffix);
         configuration = new Configuration().SetProperties(overriddenProperties);
         ValidateConfigurationViaConfigFile(configuration, connectionStringKeySuffix);
     }
     else
     {
         ValidateConfigurationViaCode(configuration.Properties);
     }
 }
Пример #5
0
        static void ValidateConfigurationViaConfigFile(Configuration configuration, string configPrefix)
        {
            if (ContainsRequiredProperties(configuration.Properties))
            {
                return;
            }

            const string errorMsg = @"In order to use NServiceBus with NHibernate you need to provide at least one connection string. You can do it via (in order of precedence):
 * specifying 'NServiceBus/Persistence/NHibernate/{0}' connection string for the {0} persister
 * specifying 'NServiceBus/Persistence' connection string that applies to all persisters
 * specifying 'NServiceBus/Persistence/connection.connection_string' or 'NServiceBus/Persistence/connection.connection_string_name' value in AppSettings or your NHibernate configuration file.
For most scenarios the 'NServiceBus/Persistence' connection string is the best option.";

            throw new InvalidOperationException(string.Format(errorMsg, configPrefix));
        }
Пример #6
0
        /// <summary>
        /// Initializes the <see cref="Configuration"/> NHibernate properties.
        /// </summary>
        /// <remarks>
        /// Configure NHibernate using the <c>&lt;hibernate-configuration&gt;</c> section
        /// from the application config file, if found, or the file <c>hibernate.cfg.xml</c> if the
        /// <c>&lt;hibernate-configuration&gt;</c> section not include the session-factory configuration.
        /// However those settings can be overwritten by our own configuration settings if specified.
        /// </remarks>
        public static void Init()
        {
            connectionStringSettingsCollection = NHibernateSettingRetriever.ConnectionStrings() ??
                                                 new ConnectionStringSettingsCollection();

            Configuration configuration = CreateNHibernateConfiguration();

            var defaultConnectionString = GetConnectionStringOrNull("NServiceBus/Persistence");
            var configurationProperties = configuration.Properties;

            var appSettingsSection = NHibernateSettingRetriever.AppSettings() ?? new NameValueCollection();

            foreach (string appSetting in appSettingsSection)
            {
                var match = PropertyRetrievalRegex.Match(appSetting);
                if (match.Success)
                {
                    configurationProperties[match.Groups[1].Value] = appSettingsSection[appSetting];
                }
            }
            if (!String.IsNullOrEmpty(defaultConnectionString))
            {
                configurationProperties[Environment.ConnectionString] = defaultConnectionString;
            }

            if (!configurationProperties.ContainsKey(Environment.Dialect))
            {
                configurationProperties[Environment.Dialect] = DefaultDialect;
            }

            TimeoutPersisterProperties = OverrideConnectionStringSettingIfNotNull(configurationProperties,
                                                                                  "NServiceBus/Persistence/NHibernate/Timeout");
            SubscriptionStorageProperties = OverrideConnectionStringSettingIfNotNull(configurationProperties,
                                                                                     "NServiceBus/Persistence/NHibernate/Subscription");
            SagaPersisterProperties = OverrideConnectionStringSettingIfNotNull(configurationProperties,
                                                                               "NServiceBus/Persistence/NHibernate/Saga");
            GatewayPersisterProperties = OverrideConnectionStringSettingIfNotNull(configurationProperties,
                                                                                  "NServiceBus/Persistence/NHibernate/Gateway");
            DistributorPersisterProperties = OverrideConnectionStringSettingIfNotNull(configurationProperties,
                                                                                      "NServiceBus/Persistence/NHibernate/Distributor");
        }
Пример #7
0
        private ISessionFactory CreateSessionFactoryFor(
            IEnumerable <string> mappingAssemblies,
            IEnumerable <EventListener> eventListeners,
            global::NHibernate.Cfg.Configuration cfg)
        {
            try
            {
                var fluentConfiguration = Fluently.Configure(cfg);

                fluentConfiguration.Mappings(
                    m =>
                {
                    foreach (var mappingAssembly in mappingAssemblies)
                    {
                        var assemblyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, MakeLoadReadyAssemblyName(mappingAssembly));
                        if (!File.Exists(assemblyPath))
                        {
                            throw new Exception(string.Format("Mapping assembly is not exist. the file name is {0}", assemblyPath));
                        }

                        var assembly = System.Reflection.Assembly.LoadFrom(assemblyPath);

                        m.HbmMappings.AddFromAssembly(assembly);
                        m.FluentMappings.AddFromAssembly(assembly).Conventions.AddAssembly(assembly);
                    }
                });



                fluentConfiguration.ExposeConfiguration(
                    e =>
                {
                    e.EventListeners.FlushEventListeners = new IFlushEventListener[] { new FixedDefaultFlushEventListener() };

                    eventListeners
                    .ToList()
                    .ForEach(eventListener =>
                    {
                        global::NHibernate.Event.ListenerType listenerType = global::NHibernate.Event.ListenerType.NotValidType;

                        System.Enum.TryParse <global::NHibernate.Event.ListenerType>(eventListener.ListenerType, true, out listenerType);

                        if (listenerType == global::NHibernate.Event.ListenerType.NotValidType)
                        {
                            throw new ApplicationException("NHibernate.Event.ListenerType not a valid type");
                        }

                        Type eventListenerType = Type.GetType(eventListener.TypeName);

                        if (eventListenerType == null)
                        {
                            throw new ApplicationException("NHibernate.Event Assembly type cannot be null.");
                        }

                        object eventListenerObject = Activator.CreateInstance(eventListenerType);

                        switch (listenerType)
                        {
                        case global::NHibernate.Event.ListenerType.PostInsert:
                            e.AppendListeners(global::NHibernate.Event.ListenerType.PostInsert,
                                              new global::NHibernate.Event.IPostInsertEventListener[] { (global::NHibernate.Event.IPostInsertEventListener)eventListenerObject });
                            break;

                        case global::NHibernate.Event.ListenerType.PostUpdate:
                            e.AppendListeners(global::NHibernate.Event.ListenerType.PostUpdate,
                                              new global::NHibernate.Event.IPostUpdateEventListener[] { (global::NHibernate.Event.IPostUpdateEventListener)eventListenerObject });
                            break;

                        case global::NHibernate.Event.ListenerType.PostDelete:
                            e.AppendListeners(global::NHibernate.Event.ListenerType.PostDelete,
                                              new global::NHibernate.Event.IPostDeleteEventListener[] { (global::NHibernate.Event.IPostDeleteEventListener)eventListenerObject });
                            break;

                        case global::NHibernate.Event.ListenerType.PreDelete:
                            e.AppendListeners(global::NHibernate.Event.ListenerType.PreDelete,
                                              new global::NHibernate.Event.IPreDeleteEventListener[] { (global::NHibernate.Event.IPreDeleteEventListener)eventListenerObject });
                            break;

                        case global::NHibernate.Event.ListenerType.PreInsert:
                            e.AppendListeners(global::NHibernate.Event.ListenerType.PreInsert,
                                              new global::NHibernate.Event.IPreInsertEventListener[] { (global::NHibernate.Event.IPreInsertEventListener)eventListenerObject });
                            break;

                        case global::NHibernate.Event.ListenerType.PreUpdate:
                            e.AppendListeners(global::NHibernate.Event.ListenerType.PreUpdate,
                                              new global::NHibernate.Event.IPreUpdateEventListener[] { (global::NHibernate.Event.IPreUpdateEventListener)eventListenerObject });
                            break;
                        }
                    });
                });

                return(fluentConfiguration.BuildSessionFactory());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }