public void CanGetImplementor()
 {
     using (IStatelessSession ss = Sfi.OpenStatelessSession())
     {
         Assert.That(ss.GetSessionImplementation(), Is.SameAs(ss));
     }
 }
 public void CanGetImplementor()
 {
     using (IStatelessSession ss = sessions.OpenStatelessSession())
     {
         ss.GetSessionImplementation().Should().Be.SameInstanceAs(ss);
     }
 }
Example #3
0
        /// <summary>
        ///     Adds NHibernate classes required to support <see cref="NHibernateRepository{T,TId}" />,
        ///     <see cref="LinqRepository{TEntity,TId}" /> instantiation from container.
        ///     <para>
        ///         <see cref="ISessionFactory" /> and <see cref="ITransactionManager" /> are registered as Singleton.
        ///     </para>
        ///     <para>
        ///         <see cref="ISession" /> is registered as Scoped (e.g. per Http request for ASP.NET Core)
        ///     </para>
        ///     <para>
        ///         <see cref="IStatelessSession" /> is transient. Since it does not tracks state, there is no reason to share it.
        ///         Stateless session must be disposed by caller
        ///         as soon as it is not used anymore.
        ///     </para>
        /// </summary>
        /// <remarks>
        ///     Repository registration needs to be done separately.
        /// </remarks>
        /// <param name="services">Service collection.</param>
        /// <param name="configureSessionFactory">
        ///     NHibernate session factory configuration.
        ///     Function should return <see cref="NHibernateSessionFactoryBuilder" /> instance,
        ///     <see cref="IServiceProvider" /> is passed to allow retrieval of configuration.
        /// </param>
        /// <param name="sessionConfigurator">Optional callback to configure new session options.</param>
        /// <param name="statelessSessionConfigurator">Optional callback to configure new stateless session options.</param>
        /// <returns>
        ///     <paramref name="services" />
        /// </returns>
        public static IServiceCollection AddNHibernateWithSingleDatabase(
            this IServiceCollection services, Func <IServiceProvider, NHibernateSessionFactoryBuilder> configureSessionFactory,
            Func <ISessionBuilder, IServiceProvider, ISession>?sessionConfigurator = null,
            Func <IStatelessSessionBuilder, IServiceProvider, IStatelessSession>?statelessSessionConfigurator = null
            )
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            if (configureSessionFactory == null)
            {
                throw new ArgumentNullException(nameof(configureSessionFactory));
            }

            services.AddSingleton(sp =>
            {
                var logger = GetLogger(sp);

                logger.Debug?.Log("Building session factory...");

                var sfBuilder      = configureSessionFactory(sp);
                var sessionFactory = sfBuilder.BuildSessionFactory();

                logger.Information?.Log("Build session factory {SessionFactoryId}", sessionFactory.GetHashCode());
                return(sessionFactory);
            });

            services.AddScoped(sp =>
            {
                var sessionFactory = sp.GetRequiredService <ISessionFactory>();
                ISession session   = sessionConfigurator == null
                    ? sessionFactory.OpenSession()
                    : sessionConfigurator(sessionFactory.WithOptions(), sp);

                GetLogger(sp).Debug?.Log("Created Session {SessionId}", session.GetSessionImplementation().SessionId);

                return(session);
            });

            services.AddScoped(sp =>
            {
                var sessionFactory        = sp.GetRequiredService <ISessionFactory>();
                IStatelessSession session = statelessSessionConfigurator == null
                    ? sessionFactory.OpenStatelessSession()
                    : statelessSessionConfigurator(sessionFactory.WithStatelessOptions(), sp);

                GetLogger(sp).Debug?.Log("Created stateless Session {SessionId}", session.GetSessionImplementation().SessionId);

                return(session);
            });

            services.AddScoped <TransactionManager>();
            services.AddTransient <INHibernateTransactionManager>(sp => sp.GetRequiredService <TransactionManager>());
            services.AddTransient <ITransactionManager>(sp => sp.GetRequiredService <TransactionManager>());

            return(services);
        }
Example #4
0
        public static IEnumerable DeepClone(this IStatelessSession session, IEnumerable entities, DeepCloneOptions opts)
        {
            var collection       = (IEnumerable)CreateNewCollection(entities.GetType());
            var resolvedEntities = new Dictionary <object, object>();

            foreach (var entity in entities)
            {
                AddItemToCollection(collection, DeepClone(session.GetSessionImplementation(), entity, opts, null, resolvedEntities));
            }
            return(collection);
        }
 private static void CancelQuery(IStatelessSession session)
 {
     try
     {
         ISessionImplementor sessionImplementor = session.GetSessionImplementation();
         if (sessionImplementor != null && sessionImplementor.Batcher != null)
         {
             sessionImplementor.Batcher.CancelLastQuery();
         }
     }
     catch (Exception)
     {
         // ignore
     }
 }
Example #6
0
 /// <summary>
 /// Flush the batcher. When batching is enabled, a stateless session is no more fully stateless. It may retain
 /// in its batcher some state waiting to be flushed to the database.
 /// </summary>
 /// <param name="session">The session.</param>
 /// <param name="cancellationToken">A cancellation token that can be used to cancel the work</param>
 public static Task FlushBatcherAsync(this IStatelessSession session, CancellationToken cancellationToken = default(CancellationToken))
 {
     if (cancellationToken.IsCancellationRequested)
     {
         return(Task.FromCanceled <object>(cancellationToken));
     }
     try
     {
         return(session.GetSessionImplementation().FlushAsync(cancellationToken));
     }
     catch (Exception ex)
     {
         return(Task.FromException <object>(ex));
     }
 }
Example #7
0
        IEnumerable <D> ImportTableData <T, D>(Func <IDataReader, D> action) where T : new()
        {
            using (var cmd = session.Connection.CreateCommand())
            {
                var persister = session.GetSessionImplementation().GetEntityPersister(null, new T()) as ILockable;
                if (persister == null)
                {
                    throw new NullReferenceException();
                }

                cmd.CommandType = CommandType.TableDirect;
                cmd.CommandText = persister.RootTableName;
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        yield return(action(reader));
                    }
                }
            }
        }
Example #8
0
 public static IQueryable <T> Query <T>(this IStatelessSession session, string entityName)
 {
     return(new NhQueryable <T>(session.GetSessionImplementation(), entityName));
 }
Example #9
0
 public static IQueryable <T> Query <T>(this IStatelessSession session)
 {
     return(new NhQueryable <T>(session.GetSessionImplementation()));
 }
 private static string GetTenantId(IStatelessSession session)
 {
     return(session.GetSessionImplementation().GetTenantIdentifier());
 }
Example #11
0
 /// <summary>
 /// Flush the batcher. When batching is enabled, a stateless session is no more fully stateless. It may retain
 /// in its batcher some state waiting to be flushed to the database.
 /// </summary>
 /// <param name="session">The session.</param>
 public static void FlushBatcher(this IStatelessSession session)
 {
     session.GetSessionImplementation().Flush();
 }
Example #12
0
 public static object DeepClone(this IStatelessSession session, object entity, System.Type entityType, DeepCloneOptions opts)
 {
     return(DeepClone(session.GetSessionImplementation(), entity, opts, entityType, new Dictionary <object, object>()));
 }
Example #13
0
 public static T DeepClone <T>(this IStatelessSession session, T entity, DeepCloneOptions opts)
 {
     return((T)DeepClone(session.GetSessionImplementation(), entity, opts, null, new Dictionary <object, object>()));
 }
Example #14
0
        public static IList <T> DeepClone <T>(this IStatelessSession session, IEnumerable <T> entities, DeepCloneOptions opts)
        {
            var resolvedEntities = new Dictionary <object, object>();

            return(entities.Select(entity => (T)DeepClone(session.GetSessionImplementation(), entity, opts, null, resolvedEntities)).ToList());
        }
Example #15
0
 public static IEnumerable <object> GetIds(IStatelessSession session, Type type, Query query)
 {
     return(GetIds(session.GetSessionImplementation(), type, query));
 }
Example #16
0
 public static SearchFactoryImpl GetSearchFactory(this IStatelessSession s)
 {
     return(GetSearchFactory(s.GetSessionImplementation()));
 }
Example #17
0
 // 6.0 TODO: consider if it should be added as a property on IStatelessSession then obsolete this, or if it should stay here as an extension method.
 /// <summary>
 /// Get the current transaction if any is ongoing, else <see langword="null" />.
 /// </summary>
 /// <param name="session">The session.</param>
 /// <returns>The current transaction or <see langword="null" />..</returns>
 public static ITransaction GetCurrentTransaction(this IStatelessSession session)
 => session.GetSessionImplementation().ConnectionManager.CurrentTransaction;
Example #18
0
 /// <summary>
 /// Get an executable instance of <c>Criteria</c>,
 /// to actually run the query.</summary>
 public ICriteria GetExecutableCriteria(IStatelessSession session)
 {
     impl.Session = session.GetSessionImplementation();
     return(impl);
 }
 public ISessionImplementor GetSessionImplementation()
 {
     return(_Session.GetSessionImplementation());
 }