简体   繁体   中英

Using NHibernate in a class library for both web and windows applications

I just changed my NHibernate application to use the Unit of Work pattern. I then continued through this tutorial to the part where it starts using HttpContext to determine whether or not the code is running in an web application. Using Visual Studio 2010 I get the error "The name 'HttpContext' does not exist in the current context". So I added a reference to System.Web and imported the namespace. The sample code then checks whether or not HttpContext.Current is null to determine whether this is a web or windows application. Is this the best way of doing that?

I would go about it a different way. Create a UnitOfWork class that has a Begin and End methods. Then your applications can use these in whichever way you want. So if you were writing a Web app you may want to Begin the unit of work on BeginRequest and End the unit of work on EndRequest. If you're writing a windows application, you might Begin a unit of work when doing an action and End it, when you're done.

The bottom line is, your data layer and unit of work implementation should be independent of the context in which it is used.

You may want to check the HttpRuntime.AppDomainId . This should never be null when a thread is hosted in a web server process. HttpContext can be null depending on when you check it in the event lifecycle. Asynchronous methods will also show a null HttpContext since they're not running in the original web thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM