c# - Detect context in Self-hosted Web Api -


in current project have windows service periodically runs tasks (topshelf/quartz.net). instead of creating separate project web service want add windows service using self-hosting features available in owin. has added benifit of not needing deploy in iis.

when i'm going implement data access layer (dal) i'll getting problems however.

all database actions done within unitofwork stored in request state , in end there commit/rollback. context determines lifecycle of unitofwork (request state). in console app use perthreadrequest state. in web environment have perhttprequeststate. mean scope of unitofwork per thread or per httprequest.

in current project have mix of both console (quartz jobs) , web (web api calls). these both need use dal aren't able use same request state it's context.

i solve manually. when using dal quartz jobs, have use perthreadrequeststate , when using dal web api calls use perhttprequeststate messy solution. when using dal should detect in wich context operating , react accordingly.

but how go detecting context?

i suggest this, using castle windsor (although principle same other ioc/di frameworks)

if(httpruntime.appdomainappid != null) //it's web app {     container.register(          component.for<iunitofwork>().implementedby<perhttprequeststate>()); } else //it's windows app {     container.register(          component.for<iunitofwork>().implementedby<perthreadrequeststate>()); } 

having said that, there caveats in using uow on thread lifestyle:

  • firstly, have make sure uow thread safe (what happens if 2 or more jobs end accessing uow @ same time?)
  • more importantly, quartz.net uses threadpool internally not create new thread every time job launched, reuse existing one. can lead leakage; uow can de-facto shared between jobs. may want use custom perquartzjob lifestyle.

both of these, however, depend on sort of usage intend put quartz service through. if don't have many, long-running, potentially overlapping crud jobs, less of concern.


Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -