Fluent NHibernate pattern for both IHttpModule and console apps

[亡魂溺海] 提交于 2019-12-05 21:03:46

This is a good question. There are a lot of different ways that this could be answered, but each answer is going to depend on how much experience you have with the different approaches out there. For example, are you familiar with TDD? Dependency injection? IoC containers? And so on.

The best advice I can give at this point is to clean up all of your existing classes so that they are not context dependent. One example of this would be modifying your repository classes so that they take an ISession object as a constructor argument instead of depending on what appears to be a singleton instance that only exists if you're in a HTTP context. This would allow you to refactor the session creation logic to a higher level outside of your domain logic.

public class PeopleRepository {
    public PeopleRepository(ISession session) {
        // store session
    }
}

In my case, I would use a IoC container to inject the session dependency. I can use this container from any type of application, whether it's a web based application using the session-per-request pattern or a console application.

There's some work you'll need to do to get NHibernate to play nice in both applications. The challenge is to minimize that work as much as possible.

I'm happy to provide more guidance. Let me know.

I often use a session object to indicate that I'm going to work with something (It's not a Unit Of Work implementation since I do not save all work until a certain point)

using (var session = SessionFactory.Create())
{
   // do all work here
}

This works since even console applications have a starting point in which the session can be initiated (for instance when the user have written a command in the console).

The session factory has a SessionCreated and a SessionDestroyed event which can be hooked by anything, in our case a nhibernate session factory.

It's a nice abstracted way to get support for a database connection or whatever without using hard dependencies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!