c# - 具有后台 worker 的 Web 应用程序的 Nhibernate session 管理策略?

标签 c# .net nhibernate sessionfactory

对于 Web 应用程序,处理 session 的一个好方法似乎是使用设置 <property name="current_session_context_class">managed_web</property> , 调用 CurrentSessionContext.Bind/Unbind在开始/结束请求上。然后我可以使用 sessionFactory.GetCurrentSession()在存储库类中。

这适用于所有页面请求。但我有后台工作人员做事并使用相同的存储库类做事。它们不在 Web 请求中运行,因此 session 处理将不起作用。

对于如何解决这个问题有什么建议吗?

最佳答案

我通过创建自己的 session 上下文类解决了这个问题:

public class HybridWebSessionContext : CurrentSessionContext
{
    private const string _itemsKey = "HybridWebSessionContext";
    [ThreadStatic] private static ISession _threadSession;

    // This constructor should be kept, otherwise NHibernate will fail to create an instance of this class.
    public HybridWebSessionContext(ISessionFactoryImplementor factory)
    {
    }

    protected override ISession Session
    {
        get
        {
            var currentContext = ReflectiveHttpContext.HttpContextCurrentGetter();
            if (currentContext != null)
            {
                var items = ReflectiveHttpContext.HttpContextItemsGetter(currentContext);
                var session = items[_itemsKey] as ISession;
                if (session != null)
                {
                    return session;
                }
            }

            return _threadSession;
        }
        set
        {
            var currentContext = ReflectiveHttpContext.HttpContextCurrentGetter();
            if (currentContext != null)
            {
                var items = ReflectiveHttpContext.HttpContextItemsGetter(currentContext);
                items[_itemsKey] = value;
                return;
            }

            _threadSession = value;
        }
    }
}

关于c# - 具有后台 worker 的 Web 应用程序的 Nhibernate session 管理策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5854238/

相关文章:

nhibernate - 优势数据库 ORM 工具或代码生成器工具

java - 为什么 hibernate 不强制您将字段标记为虚拟字段,但 nhibernate 强制您将字段标记为虚拟字段?

c# - WCF 客户端证书身份验证,服务 'SslRequireCert' 的 SSL 设置与 IIS 'Ssl, SslNegotiateCert' 的设置不匹配

.net - 匹配任何垂直空格的正则表达式

c# - 将多个参数传递给 Threading.Timer 回调方法的最佳方法是什么?

.net - Microsoft.SharePoint.PowerShell Snapin : Incorrect Windows PowerShell version 3. 0. 当前控制台支持 Window PowerShell 版本 2.0

.net - NHibernate:SQL 查询结果映射

c# - MongoDb 自定义集合序列化器

c# - 检查一个 IEnumerable 是否包含另一个 IEnumerable 的所有元素

c# - System.Environment.UserName 可以轻易伪造吗?