开发者

nhibernate current session lost after creation on background thread

开发者 https://www.devze.com 2023-01-29 05:47 出处:网络
I want to use a SQLite session to demo a wpf application; the session uses test data that has been previously created and saved to a db3 test file. I am binding the context, using code similar to what

I want to use a SQLite session to demo a wpf application; the session uses test data that has been previously created and saved to a db3 test file. I am binding the context, using code similar to what I use in normal testing - working code.

The difference here is likely that I am building the session factory and loading the test data on a background thread. To the extent that this is the problem, I am wondering if there is a different context than the "thread-static" one I am using.

I can see that the contextual session is available on the background thread. Code is below. Does anyone have a suggestion?

============

background thread code

the context is bound here, and is available when GetCurrentSession() is called

    public SqLiteDataProvider()
    {
        lock (padlock)
        {
            ...
            var session = sessionFactory.OpenSession();
            CurrentSessionContext.Bind(session);

            var pathToMother = FileHelper.GetFilePathFromDirectoryName("src", @"mother.db3");
            var conn = (SQLiteConnection)sessionFactory.GetCurrentSession().Connection;
            SQLiteDataLoader.ImportData(conn, pathToMother);

            _activitySubjectDao = new ActivitySubjectDao(sessionFactory);
        }

=============

after the background work has finished

The same ActivitySubjectDao is asked to find some data and fails when it accesses the field:

    protected ISession _session { get { return _sessionFactory.GetCurrentSession(); } }

When the dao is constructed on the background thread the session is available.

==============

update

I managed to get this to work by separating out the task of building the session factory from that of loading the test data file, and holding the factory reference in the calling class (and discovered I wasn't generating the SQLite schema in the process, which didn't help e开发者_Go百科ven a little).

This seems like a fairly common thing to want to do (building a session factory and fetching data in the background) in a desktop app, so I am still hoping someone is aware of a more elegant solution.


I guess the current session is a [ThreadStatic] variable and thus not available to the new thread?

0

精彩评论

暂无评论...
验证码 换一张
取 消