确保Repository和UnitOfWork类共享同一个nhibernate会话对象的正确方法是什么?

leo*_*ora 4 nhibernate asp.net-mvc session ninject

我有编辑和删除对象的问题,我认为它是因为我不在我的存储库类和我的unitofwork类之间共享相同的会话对象.我试图找到一些关于连接它的最佳方法的文档,所以我共享相同的会话对象.

我在mvc网站上使用ninject作为我的IOC容器.

Rob*_*aap 5

我通常将会话设置为存储库的依赖项,因此Ninject可以解析依赖项(ISession = NHibernate.ISession):

public UserRepository(ISession session)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

这是我设置绑定的方式:

kernel.Bind<ISession>().ToMethod(x => GetRequestSession()).InRequestScope();
Run Code Online (Sandbox Code Playgroud)

因此,当需要会话时,Ninject将调用GetRequestSession()来检索会话.该功能实现如下:

private static ISession GetRequestSession()
        {
            IDictionary httpContextItems = HttpContext.Current.Items;

            ISession session;
            if (!httpContextItems.Contains(MvcApplication.SESSION_KEY))
            {
                // Create an NHibernate session for this request
                session = MvcApplication.SessionFactory.OpenSession();
                httpContextItems.Add(MvcApplication.SESSION_KEY, session);
            }
            else
            {
                // Re-use the NHibernate session for this request
                session = (ISession)httpContextItems[MvcApplication.SESSION_KEY];
            }
            return session;
        }
Run Code Online (Sandbox Code Playgroud)

NHibernate会话存储在HttpContext项中.这是一个键值集合,可用于在一个请求的处理过程中存储和共享数据.

会话仅在每个请求中创建一次,并在请求期间重新使用.

MvcApplication.SESSION_KEY只是我在Global.asax中定义的一个常量字符串,它能够从HttpContext存储和检索会话.会话工厂也位于global.asax中,并在启动时创建.

您的工作单元类也可以将ISession设置为依赖项,因此Ninject也将解析此依赖项,因此使用相同的会话.另一方面,您可能不需要工作单元,因为NHibernate的ISession实现本身已经是工作类的一个单元.

我不确定这是否是最佳做法,但它对我来说非常有效.