ASP.NET MVC 中的 NHibernate 会话管理 [英] NHibernate session management in ASP.NET MVC

查看:16
本文介绍了ASP.NET MVC 中的 NHibernate 会话管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 Jeffrey Palermo 的博客文章中的 HybridSessionBuilder 类:

I am currently playing around with the HybridSessionBuilder class found on Jeffrey Palermo's blog post:

http://jeffreypalermo.com/blog/use-this-nhibernate-wrapper-to-keep-your-repository-classes-simple/

使用这个类,我的仓库看起来像这样:

Using this class, my repository looks like this:

public class UserRepository : IUserRepository
{
    private readonly ISessionBuilder _sessionBuilder;

    public UserRepository(ISessionBuilder sessionBuilder)
    {
        _sessionBuilder = sessionBuilder;
    }

    public User GetByID(string userID)
    {
        using (ISession session = _sessionBuilder.GetSession())
        {
            return session.Get<User>(userID);
        }
    }
}

这是管理 NHibernate 会话/工厂的最佳方式吗?我听说过有关工作单元和为每个 Web 请求创建会话并在最后刷新它的事情.据我所知,我目前的实现没有做任何这些.它基本上依赖于 Repository 从会话工厂中获取会话并使用它来运行查询.

Is this the best way to go about managing the NHibernate session / factory? I've heard things about Unit of Work and creating a session per web request and flushing it at the end. From what I can tell, my current implementation isn't doing any of this. It is basically relying on the Repository to grab the session from the session factory and use it to run the queries.

以这种方式访问​​数据库有什么缺陷吗?

Are there any pitfalls to doing database access this way?

推荐答案

你不应该将你的 ISession 包装在 using 语句中——将 ISessionBuilder 传递到存储库构造函数(依赖注入)的要点是调用代码负责用于控制 ISession 的生命周期.通过将其包装在 using 中,会在 ISession 上调用 Dispose(),您将无法延迟加载对象成员或将其持久化.

You should not wrap your ISession in a using statement -- the point of passing the ISessionBuilder into the repository constructor (dependency injection) is that the calling code is responsible for controlling the life cycle of the ISession. By wrapping it in a using, Dispose() is called on the ISession and you won't be able to lazy load object members or persist it.

我们通过将 ISession 传递给存储库构造函数来做类似的事情.据我了解,巴勒莫先生的代码只是添加了 ISession 的延迟初始化.我不认为这是必要的,因为如果你不打算使用它,你为什么要新建一个存储库?

We do something similar by just passing in an ISession to the repository constructor. Mr. Palermo's code, as I understand it, simply adds lazy initialization of the ISession. I don't think that's needed because why would you new up a repository if you're not going to use it?

这篇关于ASP.NET MVC 中的 NHibernate 会话管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆