Search code examples
sql-servernhibernatefluent-nhibernatesharp-architecture

Cannot set a default Nhibernate isolation level (eg via mapping)


This has been a problem that has existed on 3 projects for me.

I have tried the following:

<property name="connection.isolation">ReadCommitted</property>

Set in hibernate.cfg.xml

Using fluent nhiberate:

MsSqlConfiguration.MsSql2008.IsolationLevel(IsolationLevel.ReadCommitted);

Set in global.asax.cs

I have always been forced to set it like so:

CurrentNhibernateSession.Transaction.Begin(IsolationLevel.ReadCommitted);

which works. (I can see this using NHibernate Profiler)

The problem is now I am using sharp architecture and transaction.begin is called inside that framework and I am having trouble rebuilding it.

Is there a way to do this that works without explicitly setting it when you begin a transaction?


Solution

  • Are you certain that this is the case? If you're only verifying the isolation level by what NHProf is telling you; that could be a problem. Remember that NHProf is only reporting what the logging infrastructure in NHibernate feeds it. Perhaps the isolation level message isn't sent when you open a transaction with the default? This could probably be verified by investigating the NHibernate source.

    I would suggest using an alternate means to verify the transaction level (perhaps SQL Profiler?) before concluding that this isn't working as expected.

    Edit:

    I've had a look at the NHibernate source and can verify my hunch above. If you have a look at the AdoTransaction source you'll note that it is logging an isolation level of IsolationLevel.Unspecified when a transaction is started without specifying a specific isolation level.

    // This is the default overload you're calling:
    public void Begin()
    {
    Begin(IsolationLevel.Unspecified);
    }
    
    // This is the full method impl
    public void Begin(IsolationLevel isolationLevel)
    {
    // snip....
    
    // This is the problematic line here; it will report an isolationLevel of Unspecified.
    log.Debug(string.Format("Begin ({0})", isolationLevel));
    
    // snip...
    
    }
    

    However, the actual transaction is being started with the isolation level specified in the config a few lines down as such:

    if (isolationLevel == IsolationLevel.Unspecified)
    {
    isolationLevel = session.Factory.Settings.IsolationLevel;
    }
    

    So, it would seem that NHProf is not being entirely accurate in this instance.

    Update:

    It appears this has been fixed in the trunk version of NHibernate, so I'm guessing this is no longer an issue with NHibernate 3.xx.