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

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

问题描述

我目前与巴勒莫杰弗里的博客文章中发现的HybridSessionBuilder类打转转:

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

<一个href=\"http://jeffreypalermo.com/blog/use-this-nhibernate-wrapper-to-keep-your-repository-classes-simple/\">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请求的会话,并在年底刷新它的东西。从我可以告诉,我目前的实施没有做任何这一点。它基本上是依靠库抢在会话工厂的会话,并用它来运行查询。

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到储备库构造(依赖注入)的一点是,调用code是负责控制的ISession的生命周期。通过在使用包装它,处置()被调用的ISession的,你将不能够延迟加载对象成员或坚持它。

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到仓库构造类似的东西。巴勒莫先生的code,据我所知,只是添加的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天全站免登陆