Я хочу использовать контекст сеанса 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);