How to implement the Open Session in View template in NHibernate?

I am using ASP.NET MVC + NHibernate + Fluent NHibernate and have a lazy loading problem.

In this question ( How to fix the NHibernate lazy loading error "session or session is not closed" , ), I found that I need to implement the Open Session in View template, but I do not know how to do it.

In my repository classes, I use methods like

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(); } } } 

And this is my Factory session helper class:

 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(); } } 

Can anyone help me implement an Open Session in a view?

Thanks.

+1
source share
1 answer

This was already asked, but I do not remember where to find it. When you do the following or something similar, you have what you want and code duplication will decrease in your repositories as a bonus.

 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); } } 

You can also manage a session with an ioc container and a single working shell instead of the current session context.

+2
source

Source: https://habr.com/ru/post/1305169/


All Articles