C# NHibernate当前会话上下文错误“;对象引用未设置为对象的实例;
我想使用NHibernate会话上下文 我在hibernate.cfg.xml中的内容:C# NHibernate当前会话上下文错误“;对象引用未设置为对象的实例;,c#,xml,nhibernate,C#,Xml,Nhibernate,我想使用NHibernate会话上下文 我在hibernate.cfg.xml中的内容: <property name="current_session_context_class">web</property> 我得到一个错误: System.NullReferenceException: Object reference not set to an instance of an object. at lambda_method(Closure , Objec
<property name="current_session_context_class">web</property>
我得到一个错误:
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());
==编辑2==
正如我刚刚发现的,当我试图将会话绑定到CurrentSessionContext时,它似乎抛出了NullReferenceExeption
CurrentSessionContext.Bind(session);
请参阅
NHibernate.Context.WebSessionContext
可能是您要查找的内容。谢谢,但是如果我使用NHibernate.Context.WebSessionContext
我会收到相同的错误(如屏幕截图所示),您是否将会话绑定到当前会话上下文?在您的代码中应该有类似于Configuration=new Configuration()的内容;Configure.Configure();configuration.AddAssembly(Assembly.getExecutionGassembly());ISessionFactory sf=configuration.BuildSessionFactory();ISession session=sf.OpenSession();CurrentSessionContext.Bind(会话)代码>请参见我的编辑,如何创建sessionfactory。在那一刻,我希望会话只是null
,而不是错误。会话绑定在.OpenSession()Hm上,在我拥有的NHibernate 5.1版中,SessionFactoryHelper
没有实例
成员。另外,我会在调用session.BeginTransaction()之前进行绑定
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);
}
CurrentSessionContext.Bind(session);