用于控制台应用程序的spring.netnhibernate会话管理

本文关键字:netnhibernate 会话 管理 spring 控制台 应用程序 用于 | 更新日期: 2023-09-27 18:29:36

我知道spring可以为您管理会话,如果配置如下:

<object name="SessionFactory"
                    type="MyApp.DAL.DAOs.SessionFactoryObject, Leverate.Crm.CrmService.DAL">
<!--My class which inherits from LocalSessionFactoryObject and defines the mapping assemblies to be used--> 
    <property name="ExposeTransactionAwareSessionFactory" value="true" />
    <property name="DbProvider" ref="DbProvider"/>
    <property name="HibernateProperties">
      <dictionary>
        <entry key="cache.use_second_level_cache" value="false"/>
        <entry key="command_timeout" value="180"/>
        <entry key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
        <entry key="dialect" value="NHibernate.Dialect.MsSql2005Dialect"/>
        <entry key="connection.driver_class" value="NHibernate.Driver.SqlClientDriver"/>
      </dictionary>
    </property>
    <property name="SchemaUpdate" value="false"/>
  </object>
    <db:provider id="DbProvider"
                   provider="SqlServer-1.1"
                   connectionString="Data Source=local;Initial Catalog=northwind;Trusted_Connection=Yes;"/>

问题是,使用SessionFactory.GetCurrentSession()会引发'No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here'异常。

我看到一些答案说,在web上下文中,您必须使用openSessionInView(或类似的)httpModule。但是你在控制台应用程序(或者windows服务)中做什么呢?

用于控制台应用程序的spring.netnhibernate会话管理

您将会话工厂公开为事务感知会话工厂,这意味着Spring将为您管理事务中正确封装的所有方法的会话。为了用spring将数据访问方法封装在事务中,可以使用声明性(属性驱动)或编程方法。