我想使用NHibernate会话上下文。
我的hibernate.cfg.xml中包含的内容:
<property name="current_session_context_class">web</property>
但是现在当我尝试检查会话是否绑定时:
if (CurrentSessionContext.HasBind(mySessionFactory))
我得到了错误:
System.NullReferenceException: Object reference not set to an instance of an
object.
at lambda_method(Closure , Object )
at NHibernate.Context.WebSessionContext.GetMap()
at NHibernate.Context.MapBasedSessionContext.get_Session()
at NHibernate.Context.CurrentSessionContext.HasBind(ISessionFactory factory)
当我检查sessionFactory
时,我发现CurrentSessionContext抛出错误:
我以前从未使用过CurrentSessionContext。因此,我很高兴获得帮助。谢谢!
==编辑==
这是我创建会话工厂所必须的:
public Configuration GetConfiguration()
{
configuration = new Configuration();
// Configure NHibernate with the hibernate.cfg.xml file
configuration.Configure(Path.Combine(System.Environment.CurrentDirectory, "hibernate.cfg.xml"));
// Create new model mapper
var mapper = new ModelMapper();
// Get all types of the assembly and add them to the mapper
mapper.AddMappings(assembly.GetExportedTypes());
// Compile the mappings
var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
// Add the mappings (using executing assembly)
configuration.AddMapping(mapping);
return configuration;
}
我叫:
private readonly Dictionary<string, ISessionFactory> sessionFactories = new Dictionary<string, ISessionFactory>();
sessionFactories.Add("hibernate.cfg.xml", GetConfiguration(assembly).BuildSessionFactory());
还有我的OpenSession()
public void OpenSession(string configFile)
{
if (CurrentSessionContext.HasBind(SessionFactoryHelper.Instance.GetSessionFactoryByConfigFile(configFile)))
throw new Exception("There is already a session bind to current context");
// Get new session from the session factory
var session = SessionFactoryHelper.Instance.GetSessionFactoryByConfigFile(configFile).OpenSession();
// Start the transaction
session.BeginTransaction();
// Bind the session to the currentsession context
CurrentSessionContext.Bind(session);
}
==编辑2 ==
正如我刚刚发现的那样,当我尝试将会话绑定到它时,似乎CurrentSessionContext抛出了NullReferenceExeption
。
CurrentSessionContext.Bind(session);