【问题标题】:How implement the Open Session in View pattern in NHibernate?如何在 NHibernate 中实现 Open Session in View 模式?
【发布时间】:2011-02-01 07:25:21
【问题描述】:

我正在使用 ASP.NET MVC + NHibernate + Fluent NHibernate 并且遇到延迟加载问题。

通过这个问题 (How to fix a NHibernate lazy loading error "no session or session was closed"?),我发现我必须实现 Open Session in View 模式,但我不知道如何。

在我的存储库类中,我使用这样的方法

    public ImageGallery GetById(int id) {
        using(ISession session = NHibernateSessionFactory.OpenSession()) {
            return session.Get<ImageGallery>(id);
        }
    }

    public void Add(ImageGallery imageGallery) {
        using(ISession session = NHibernateSessionFactory.OpenSession()) {
            using(ITransaction transaction = session.BeginTransaction()) {
                session.Save(imageGallery);
                transaction.Commit();
            }
        }
    }

这是我的会话工厂助手类:

public class NHibernateSessionFactory {
    private static ISessionFactory _sessionFactory;
    private static ISessionFactory SessionFactory {
        get {
            if(_sessionFactory == null) {
                _sessionFactory = Fluently.Configure()
                    .Database(MySQLConfiguration.Standard.ConnectionString(MyConnString))
                    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<ImageGalleryMap>())
                    .ExposeConfiguration(c => c.Properties.Add("hbm2ddl.keywords", "none"))
                    .BuildSessionFactory();
            }
            return _sessionFactory;
        }
    }
    public static ISession OpenSession() {
        return SessionFactory.OpenSession();
    }
}

有人可以帮我实现 Open Session in View 模式吗?

谢谢。

【问题讨论】:

    标签: asp.net-mvc nhibernate design-patterns fluent-nhibernate


    【解决方案1】:

    这已经被问过了,但我不记得在哪里可以找到它。当您执行以下操作或类似操作时,您将获得所需的内容,并且在您的存储库中减少一些代码重复作为奖励。

     

    public class Repository
    {
      private readonly ISession session;
    
      public Repository()
      {
        session = CurrentSessionContext.CurrentSession();
      } 
    
      public ImageGallery GetById(int id) 
      {
        return session.Get<ImageGallery>(id);
      }
    
      public void Add(ImageGallery imageGallery)
      {
        session.Save(imageGallery);
      }
    }
    

    您还可以使用 ioc 容器和工作单元包装器而不是当前会话上下文来管理会话。

    【讨论】:

    • 我建议对存储库类使用手动依赖注入。也就是说,将 ISession 传递到存储库的构造函数中。
    • “手动依赖注入”的唯一原因是单元测试。它没有像通过自动注入解决依赖关系那样的松散耦合。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多