Fluent Nhibernate ignore CurrentSessionContext - or having trouble bringging the current session

1

I have the following fluent NHibernate settings:

public class NHibernateHelper : INHibernateHelper
    {
        private readonly string _connectionString;
        private readonly object _lockObject = new object();
        private ISessionFactory _sessionFactory;

        public NHibernateHelper(IConfiguration configuration)
        {
            _connectionString = configuration["ConnectionString"];
        }

        public ISessionFactory SessionFactory
        {
            get
            { if (_sessionFactory == null) 
                    CreateSessionFactory(); 
                return _sessionFactory; 
            }
        }
        private void CreateSessionFactory()
        {
            lock (_lockObject)
            {
                 _sessionFactory = Fluently.Configure()
                .Database(MySQLConfiguration.Standard.ConnectionString(_connectionString).ShowSql())
                .CurrentSessionContext<WebSessionContext>()// this is a webapp
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<BaseEntity>())
                .ExposeConfiguration(
                      cfg =>
                      {
                          cfg.SetProperty("current_session_context_class", "web");
                      }).BuildSessionFactory();
         }
       }
      }

This is how I initialize the session and the transaction, with a debugger I see that the bellow code is executed on time with no exceptions thrown:

public class TransactionFilter : IActionFilter
{
    private readonly INHibernateHelper nhibernateHelpe;
    private ITransaction transaction;
    public TransactionFilter(INHibernateHelper nhibernateHelpe)
    {
        this.nhibernateHelpe = nhibernateHelpe;
    }
    public NHibernate.ISession session { get; private set; }
    public void OnActionExecuted(ActionExecutedContext context)
    {
        this.transaction.Commit();
        this.transaction.Dispose();
        this.session.Dispose();
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        this.session = nhibernateHelpe.SessionFactory.OpenSession();
        this.transaction = this.session.BeginTransaction();

    }
}

when I call to:

 res = nhibernateHelper.SessionFactory.GetCurrentSession().Load<T>(id);

I get the exception:

System.TypeInitializationException
  HResult=0x80131534
  Message=The type initializer for 'NHibernate.Context.ReflectiveHttpContext' threw an exception.
  Source=NHibernate
  StackTrace:
   at NHibernate.Context.ReflectiveHttpContext.get_HttpContextCurrentItems()
   at NHibernate.Context.WebSessionContext.GetMap()
   at NHibernate.Context.MapBasedSessionContext.GetConcreteMap()
   at NHibernate.Context.MapBasedSessionContext.get_Session()
   at NHibernate.Context.CurrentSessionContext.CurrentSession()
   at NHibernate.Impl.SessionFactoryImpl.GetCurrentSession()
   at Lob.Backend.Repository.BaseRepository`1.FindById(Int32 id) in C:\work\projects\ey-server-net\Lob.Backend\Repository\BaseRepository.cs:line 69
   at Lob.Backend.Controllers.ResearchController.Id(Int32 id) in C:\work\projects\ey-server-net\Lob.Backend\Controllers\ResearchController.cs:line 54
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()

Inner Exception 1:
NullReferenceException: Object reference not set to an instance of an object.
fluent-nhibernate
asked on Stack Overflow Sep 16, 2019 by SexyMF • edited Sep 24, 2019 by SexyMF

2 Answers

0

Based on the exception it looks like ioc binding issue. GetCurrentSession() returns session bound to a current context, which means if the instance of INHibernateHelper instance in the action controller is not the same instance that is used by your base repository it will throw exception as there is no context.

You'd need to configure INHibernateHelper in your IoC bindings as a singleton - this ensures you will have access to current session

answered on Stack Overflow Sep 18, 2019 by tchrikch
0

WebSessionContext is a wrapper around HttpContext.Current. And so it is not supported in AspNet Core because there is no HttpContext.Current.

You would need to implement own ICurrentSessionContext if you want to use that pattern. Here is a code snipped that could help: https://github.com/nhibernate/nhibernate-core/issues/1632#issuecomment-377704293

answered on Stack Overflow Sep 18, 2019 by hazzik

User contributions licensed under CC BY-SA 3.0