Exemplo n.º 1
0
        public AmbientContextSuppressor()
        {
            _savedScope = SessionScope.GetAmbientScope();

            // We're hiding the ambient scope but not removing its instance
            // altogether. This is to be tolerant to some programming errors.
            //
            // Suppose we removed the ambient scope instance here. If someone
            // was to start a parallel task without suppressing
            // the ambient context and then tried to suppress the ambient
            // context within the parallel task while the original flow
            // of execution was still ongoing (a strange thing to do, I know,
            // but I'm sure this is going to happen), we would end up
            // removing the ambient context instance of the original flow
            // of execution from within the parallel flow of execution!
            //
            // As a result, any code in the original flow of execution
            // that would attempt to access the ambient scope would end up
            // with a null value since we removed the instance.
            //
            // It would be a fairly nasty bug to track down. So don't let
            // that happen. Hiding the ambient scope (i.e. clearing the CallContext
            // in our execution flow but leaving the ambient scope instance untouched)
            // is safe.
            SessionScope.HideAmbientScope();
        }
Exemplo n.º 2
0
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            if (_savedScope != null)
            {
                SessionScope.SetAmbientScope(_savedScope);
                _savedScope = null;
            }

            _disposed = true;
        }
        /// <summary>
        /// Makes the provided 'SessionScope' available as the the ambient scope via the CallContext.
        /// </summary>
        internal static void SetAmbientScope(SessionScope newAmbientScope)
        {
            if (newAmbientScope == null)
            {
                throw new ArgumentNullException(nameof(newAmbientScope));
            }

            var current = CallContext.LogicalGetData(AmbientDbContextScopeKey) as InstanceIdentifier;

            if (current == newAmbientScope._instanceIdentifier)
            {
                return;
            }

            // Store the new scope's instance identifier in the CallContext, making it the ambient scope
            CallContext.LogicalSetData(AmbientDbContextScopeKey, newAmbientScope._instanceIdentifier);

            // Keep track of this instance (or do nothing if we're already tracking it)
            SessionScopeInstances.GetValue(newAmbientScope._instanceIdentifier, key => newAmbientScope);
        }
Exemplo n.º 4
0
 public SessionReadOnlyScope(SessionScopeOption joiningOption, IsolationLevel?isolationLevel, ISessionFactory sessionFactory, IInterceptor sessionLocalInterceptor)
 {
     _internalScope = new SessionScope(joiningOption, true, isolationLevel, sessionFactory, sessionLocalInterceptor);
 }
        public ISession Get()
        {
            SessionScope ambientSessionScope = SessionScope.GetAmbientScope();

            return(ambientSessionScope?.Session);
        }
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            // Commit / Rollback and dispose our ISession instance
            if (!_nested)
            {
                if (!_completed)
                {
                    // Do our best to clean up as much as we can but don't throw here as it's too late anyway.
                    try
                    {
                        if (_readOnly)
                        {
                            // Disposing a read-only scope before having called its SaveChanges() method
                            // is the normal and expected behavior. Read-only scopes get committed automatically.
                            CommitInternal();
                        }
                        else
                        {
                            // Disposing a read/write scope before having called its SaveChanges() method
                            // indicates that something went wrong and that all changes should be rolled-back.
                            RollbackInternal();
                        }
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(e);
                    }

                    _completed = true;
                }

                if (_session.IsValueCreated)
                {
                    if (_session.Value.IsOpen)
                    {
                        _session.Value.Close();
                    }

                    _session.Value.Dispose();
                }
            }

            // Pop ourself from the ambient scope stack
            SessionScope currentAmbientScope = GetAmbientScope();

            if (currentAmbientScope != this) // This is a serious programming error. Worth throwing here.
            {
                throw new InvalidOperationException("SessionScope instances must be disposed of in the order in which they were created!");
            }

            RemoveAmbientScope();

            if (_parentScope != null)
            {
                if (_parentScope._disposed)
                {
                    /*
                     * If our parent scope has been disposed before us, it can only mean one thing:
                     * someone started a parallel flow of execution and forgot to suppress the
                     * ambient context before doing so. And we've been created in that parallel flow.
                     *
                     * Since the CallContext flows through all async points, the ambient scope in the
                     * main flow of execution ended up becoming the ambient scope in this parallel flow
                     * of execution as well. So when we were created, we captured it as our "parent scope".
                     *
                     * The main flow of execution then completed while our flow was still ongoing. When
                     * the main flow of execution completed, the ambient scope there (which we think is our
                     * parent scope) got disposed of as it should.
                     *
                     * So here we are: our parent scope isn't actually our parent scope. It was the ambient
                     * scope in the main flow of execution from which we branched off. We should never have seen
                     * it. Whoever wrote the code that created this parallel task should have suppressed
                     * the ambient context before creating the task - that way we wouldn't have captured
                     * this bogus parent scope.
                     *
                     * While this is definitely a programming error, it's not worth throwing here. We can only
                     * be in one of two scenario:
                     *
                     * - If the developer who created the parallel task was mindful to force the creation of
                     * a new scope in the parallel task (with ISessionScopeFactory.CreateNew() instead of
                     * JoinOrCreate()) then no harm has been done. We haven't tried to access the same ISession
                     * instance from multiple threads.
                     *
                     * - If this was not the case, they probably already got an exception complaining about the same
                     * ISession being accessed from multiple threads simultaneously (or a related error like multiple
                     * active result sets on a DataReader, which is caused by attempting to execute several queries
                     * in parallel on the same ISession instance). So the code has already blow up.
                     *
                     * So just record a warning here. Hopefully someone will see it and will fix the code.
                     */

                    string message = @"PROGRAMMING ERROR - When attempting to dispose a SessionScope, we found that our parent SessionScope has already been disposed! This means that someone started a parallel flow of execution (e.g. created a TPL task, created a thread or enqueued a work item on the ThreadPool) within the context of a SessionScope without suppressing the ambient context first.

In order to fix this:
1) Look at the stack trace below - this is the stack trace of the parallel task in question.
2) Find out where this parallel task was created.
3) Change the code so that the ambient context is suppressed before the parallel task is created. You can do this with ISessionScopeFactory.SuppressAmbientContext() (wrap the parallel task creation code block in this). 

Stack Trace:
" + Environment.StackTrace;

                    System.Diagnostics.Debug.WriteLine(message);
                }
                else
                {
                    SetAmbientScope(_parentScope);
                }
            }

            _disposed = true;
        }
        public SessionScope(SessionScopeOption joiningOption, bool readOnly, IsolationLevel?isolationLevel, ISessionFactory sessionFactory, IInterceptor sessionLocalInterceptor)
        {
            if (isolationLevel.HasValue && joiningOption == SessionScopeOption.JoinExisting)
            {
                throw new ArgumentException("Cannot join an ambient SessionScope when an explicit database transaction is required. When requiring explicit database transactions to be used (i.e. when the 'isolationLevel' parameter is set), you must not also ask to join the ambient context (i.e. the 'joinAmbient' parameter must be set to false).");
            }

            if (sessionFactory == null)
            {
                throw new ArgumentNullException(nameof(sessionFactory));
            }

            _disposed  = false;
            _completed = false;
            _readOnly  = readOnly;

            _parentScope = GetAmbientScope();
            if (_parentScope != null && joiningOption == SessionScopeOption.JoinExisting)
            {
                if (_parentScope._readOnly && !_readOnly)
                {
                    throw new InvalidOperationException("Cannot nest a read/write SessionScope within a read-only SessionScope.");
                }

                _nested  = true;
                _session = _parentScope._session;
            }
            else
            {
                _nested  = false;
                _session = new Lazy <ISession>(() => {
                    ISession session;

                    if (sessionLocalInterceptor == null)
                    {
                        session = sessionFactory.OpenSession();
                    }
                    else
                    {
                        session = sessionFactory.WithOptions()
                                  .Interceptor(sessionLocalInterceptor)
                                  .OpenSession();
                    }

                    if (readOnly)
                    {
                        // REVIEW WC
                        session.DefaultReadOnly = true;
                    }

                    if (isolationLevel.HasValue)
                    {
                        session.BeginTransaction(isolationLevel.Value);
                    }
                    else
                    {
                        session.BeginTransaction();
                    }

                    return(session);
                });
            }

            SetAmbientScope(this);
        }