Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6820933
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T21:29:05+00:00 2026-05-26T21:29:05+00:00

I’ve got a problem with NHibernate 3.2. I’m porting a solution we used in

  • 0

I’ve got a problem with NHibernate 3.2.

I’m porting a solution we used in a Java application, to a c# 4.0 application.
What we want to create is a simple mechanism that handle session and transaction through the NHibernate SessionFactory, letting the transaction be instantiated by the unit-of-work beginner, and then being used by all the partecipant method, without even know that they are part of a bigger unit-of-work. But if you call these sub methods directly, they’ll handle their own transaction.

In these question I explained better our approach.
We first did it in Java world, and it works pretty fine.
Now I’m porting the the same approach to c# 4.0, using NHibernate 3.2.

The class which is going to handle all my session and transaction is colled OperationManager (you could think to UnitOfWorkManager):

public class OperationManager : IDisposable
{
    private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

    ITransaction tx = null;
    ISession session = null;
    bool isInternalTransaction = false;

    public ISession BeginOperation()
    {
        logger.Debug("Thread : " + System.Threading.Thread.CurrentThread.ManagedThreadId);
        session = PersistenceManager.Istance.GetSession();
        if (session.Transaction.IsActive)
        {
            isInternalTransaction = false;
            tx = session.Transaction;                               
            logger.Debug(GetCallerClassDotMethod() + " is binding to transaction " + tx.GetHashCode());
        }
        else
        {
            isInternalTransaction = true;
            tx = session.Transaction;
            tx.Begin(); 
            logger.Debug("Transaction " + tx.GetHashCode() + " created by " + GetCallerClassDotMethod());
        }
        logger.Debug("Session hash " + session.GetHashCode());
        return session;
    }

    private String GetCallerClassDotMethod() {
        // needed to get the Business Logic method calling the public methods
        var st = new StackTrace();
        var sf = st.GetFrame(2);
        var methodReference = sf.GetMethod().Name;
        var classReference = sf.GetMethod().DeclaringType.FullName;
        return string.Concat(classReference, ".", methodReference);
    }

    public void CommitOperation()
    {
        if (isInternalTransaction)
        {                
            tx.Commit();
            logger.Debug(GetCallerClassDotMethod() + " is committing transaction " + tx.GetHashCode());
        }
    }

    public void RollbackOperation()
    {
        if (isInternalTransaction)
        {
            tx.Rollback();                
            logger.Debug(GetCallerClassDotMethod() + " is rolling back transaction " + tx.GetHashCode());                
        }
    }

    public void Dispose()
    {
        tx.Dispose();
        session.Dispose();
    }
}

Here’s my PersistenceManager

internal class PersistenceManager : IDisposable
{
    private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
    private static PersistenceManager _istance;
    private ISessionFactory _SessionFactory;
    private static Object _lock = new Object();

    public static PersistenceManager Istance
    {
        get
        {
            lock (_lock)
            {
                if (_istance == null)
                {
                    _istance = new PersistenceManager();
                    logger.Info("New PersistenceManager instance created");
                }
                return _istance;
            }
        }
    }

    private PersistenceManager()
    {
        // Initialize
        Configuration cfg = new Configuration();
        cfg.Configure(ConfigurationManager.ConfigurationManager.Istance.hibernateConfiguration);
        cfg.SetProperty("connection.connection_string", ConfigurationManager.ConfigurationManager.Istance.connectionString);

        /* Note: The AddAssembly() method requires that mappings be 
         * contained in hbm.xml files whose BuildAction properties 
         * are set to ‘Embedded Resource’. */

        // Add class mappings to configuration object
        System.Reflection.Assembly thisAssembly = typeof(PersistenceManager).Assembly;
        cfg.AddAssembly(thisAssembly);            

        // Create session factory from configuration object
        _SessionFactory = cfg.BuildSessionFactory();
    }



    public void Dispose()
    {
        _SessionFactory.Dispose();
    }


    /// <summary>
    /// Close this Persistence Manager and release all resources (connection pools, etc). It is the responsibility of the application to ensure that there are no open Sessions before calling Close().
    /// </summary>
    public void Close()
    {
        _SessionFactory.Close();
    }


    public ISession GetSession()
    {
        return _SessionFactory.OpenSession();
    }

}

Now, whenever I need to access DB, I use an OperationManager instance to grab the current session (and current transaction) and use it for al my need.
An example is found here:

public IList<Agency> getAllAgencies()
    {
        using (var om = new OperationManager())
        {
            try
            {
                om.BeginOperation();
                var result = base.Load<Agency>().ToList();
                om.CommitOperation();
                return result;
            }
            catch (Exception ex)
            {
                om.RollbackOperation();
                throw ex;
            }
        }
    }

and in the base class I have

protected IQueryable<T> Load<T>() where T : Model.ModelEntity
    {
        using (var om = new OperationManager())
        {
            try
            {
                var session = om.BeginOperation();
                var entities = session.Query<T>();
                om.CommitOperation();
                return entities;
            }
            catch (Exception ex)
            {
                om.RollbackOperation();
                throw new Exception(msg, ex);
            }
        }
    }

The problem is that, even if I configured NHibernate session factory to work on a per-thread model using <property name="current_session_context_class">thread_static</property>, the two calls to OperationManager.beginOperation() give back a difference sessione, thus with different transaction.

Can anybody tell me why this is happening?

Edited:
Following the suggestion of Fredy Treboux, I tried to implement a mechanism that create a new session or just get the current one, using CurrentSessionContext static object of NHibernate.
Too bad, this still don’t work.
After cleaning up the code, avoiding everything related on transaction, session, unit-of-work, etc, I wrote a very trivial class, and I figured out that using

<property name="current_session_context_class">thread_static</property> 

bring me a problem with sql server 2008 db.
Using that context class, on a classic SessionFactory.OpenSession() approach and then loading some data, I get the following error:

System.Data.SqlClient.SqlException: A transport-level error has occurred when receiving results from the server. (provider: Shared Memory Provider, error: 0 - Invalid Handle.)

Any idea why this happen?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T21:29:05+00:00Added an answer on May 26, 2026 at 9:29 pm

    You are calling SessionFactory.OpenSession() every time.
    This will open and return a new session regardless of everything else.

    Altough I won’t be eager to recommend this approach, for it to work, you’ll need to do some sort of reference counting on your PersistenceManager to know when to open a new session and when to release it.

    The current_session_context_class is not affecting this, since it only controls what SessionFactory.GetCurrentSession() returns, and the ThreadStaticSessionContext (thread_static) has to be manipulated manually anyways through Bind/Unbind.

    Approach I would recoomend

    Well, two things.

    First, I like to define a specific layer to handle sessions/transactions.
    What I’m trying to say is that if I got methods A and B, and A may use B but B may also be used from outside I would prefer to have a method C that defines the session/transaction boundary for B.

    So, A and C are the methods that are publicly available, and both use B (even when in C you’re almost directly calling B).

    The second thing is that you may be better of using a session context manager already available like the ones you can find in many NHibernate based libraries (e.g. http://code.google.com/p/unhaddins/) or even if you decide to go on implementing your own, try to make it fit the SessionContext machinery available in NHibernate so you’ll be able to call SessionFactory.GetCurrentSession() to get the session and be compatible with other contexts/methods of doing the same.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to create an if statement in PHP that prevents a single post
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I used javascript for loading a picture on my website depending on which small

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.