Gaurav Arora
Gaurav Arora

Reputation: 2324

MVC3 Razor with nHibernate

As a famous ORM we decided to user nHIbernate with asp.net mvc3. We set up our project in the following way:

  1. NHibernate Repository [contains mappings, service and repositories for nhibernate]
  2. MVC3 [this is a UI]
  3. Test MVC NHibernate [this is a test project with NUnit]

In above, [] text are written ti make clear about the layers.

Everything is working fine, means all Unit Tests are passed for mapping, insert, update, delete operations. Unfotunately, when we are doing the same operation from our mvc3 application then it threw following error:

   "An exception occurred during configuration of persistence layer."   

Full stack-trace is as follow:

   at NHibernate.Cfg.ConfigurationSchema.HibernateConfiguration..ctor(XmlReader hbConfigurationReader, Boolean fromAppSetting) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Cfg\ConfigurationSchema\HibernateConfiguration.cs:line 55
   at NHibernate.Cfg.ConfigurationSchema.HibernateConfiguration..ctor(XmlReader hbConfigurationReader) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Cfg\ConfigurationSchema\HibernateConfiguration.cs:line 36
   at NHibernate.Cfg.Configuration.Configure(XmlReader textReader) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Cfg\Configuration.cs:line 1511
   at NHibernate.Cfg.Configuration.Configure(String fileName, Boolean ignoreSessionFactoryConfig) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Cfg\Configuration.cs:line 1433
   at NHibernate.Cfg.Configuration.Configure(String fileName) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Cfg\Configuration.cs:line 1418
   at NHibernate.Cfg.Configuration.Configure() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Cfg\Configuration.cs:line 1404
   at examplemvcapp.NHibernateRepository..ctor() in D:\example\examplemvcapp-NHExample\examplemvcapp\NHibernateRepository.cs:line 33
   at examplemvcapp_NHExample.UI.Models.CreateAppraisalModel..ctor() in D:\example\examplemvcapp-NHExample\examplemvcapp-NHExample.UI\Models\Department.cs:line 70  

Please note that all configuration settings for NHIbernate are same in MVC3 app as in Test project.

Following is the guy where we got the exception :

using (var nhr = new NHibernateRepository())
{
    this.Departments = nhr.GetAll<Departments>().Select(x => new SelectListItem 
        {
            Text = x.Departmentdescription, Value = x.Id.ToString()
        });
}

Above will bring up to following and threw an exception :

public NHibernateRepository()
{
    if (sessionFactory == null)
    {
        config = new Configuration();
        config.Configure();
        config.AddAssembly(typeof(NHibernateRepository).Assembly);
        sessionFactory = config.BuildSessionFactory();
    }
    Session = sessionFactory.OpenSession();
    transaction = Session.BeginTransaction();
    Rollback = false;
}

The above is working fine in Test project :

using (var nhr = new NHibernateRepository())
{
    var DeptList = nhr.GetAll<Departments>();
}

Following is the hibernate.cfg.xml file placed in NHibernateRepository project:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">  
  <session-factory>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.connection_string">Data Source=(local);Initial Catalog=myDatabaseName;Integrated Security=True</property>
    <property name="show_sql">true</property>
    <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
    <property name="cache.use_query_cache">false</property>
    <property name="adonet.batch_size">100</property>
    <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>

  </session-factory>
</hibernate-configuration>

Apart from above this project is having all dlls required for NHibernate.

In Test project there is no special configuration settings just we add reference of Repository project and other assemblies required for this and its working fine.

The same has been maintained in MVC3 application project.

Any help in this regard is most appreciable.

Regards

Upvotes: 0

Views: 1471

Answers (2)

Gaurav Arora
Gaurav Arora

Reputation: 2324

Per @Michael - I am closing this thread by supplying following answer, I have found during my reasearch.

There are two things we need to do for the proper solution;

  1. If using XML files we need to set them as Embedded in properties
  2. If not using xml files - we need to make the compiled

To set above just select file name from solution explorere and press F4 or See property window by Right clicking on the file name and then property link.

Thanks everyone - who answered for the above question.

Upvotes: 1

Josh Anderson
Josh Anderson

Reputation: 6005

I'm not sure if this will address your current issues, but I do have a few recommendations. First, implement session-per-request session management, either in your Global.asax or (my preference) via an HttpModule. Here's a simple example:

public class NHHttpModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.EndRequest += ApplicationEndRequest;
        context.BeginRequest += ApplicationBeginRequest;
    }

    public void ApplicationBeginRequest(object sender, EventArgs e)
    {
        CurrentSessionContext.Bind(SessionFactory.GetNewSession());
    }

    public void ApplicationEndRequest(object sender, EventArgs e)
    {
        var currentSession = CurrentSessionContext.Unbind(SessionFactory.GetSessionFactory());
        currentSession.Close();
        currentSession.Dispose();
    }

    public void Dispose()
    {
        // Do nothing
    }
}

Note that this also binds the current session context during the request management.

Also, ensure that you're setting the proper session context. Tests should probably use the thread context, but web applications should use the web context. I personally configure this via Fluent NHibernate, but I believe in the XML config files it would appear as:

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

Again, I generally configure with FNH, so verify that.

Upvotes: 1

Related Questions