ServiceStack NHibernate Session per request

后端 未结 3 591
名媛妹妹
名媛妹妹 2021-01-12 05:01

I am starting to build an app, and I\'m planning to use ServiceStack. Just want to know what are the best practices/good approaches for handling NHibernate ISession or, othe

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-12 05:49

    I know this is an old question, but I figured I'd go ahead and show anyone who is still interested in an alternate answer how we just did this.

    We are using the ServiceRunner in the new ServiceStack API thusly:

    public class BaseServiceRunner : ServiceRunner
    {
        public BaseServiceRunner(AppHost appHost, ActionContext actionContext)
        : base(appHost, actionContext) { }
    
        public override void OnBeforeExecute(IRequestContext requestContext, TRequest request)
        {
            var req = request as MyRequestType;
    
            if(req == null)
                base.OnBeforeExecute(requestContext, request);
    
            var factory = TryResolve();
            var session = factory.OpenSession();
            var trans = session.BeginTransaction(IsolationLevel.ReadCommitted);
    
            requestContext.SetItem("session", session);
            requestContext.SetItem("transaction", trans);
        }        
    
        public override object OnAfterExecute(IRequestContext requestContext, object response)
        {
            var trans = requestContext.GetItem("transaction") as ITransaction;
            if (trans != null && trans.IsActive)
                trans.Commit();
    
            var session = requestContext.GetItem("session") as ISession;
            if (session != null)
            {
                session.Flush();
                session.Close();
            }
    
            return base.OnAfterExecute(requestContext, response);
        }
    
        public override object HandleException(IRequestContext requestContext, TRequest request, Exception ex)
        {
            var req = request as MyRequestType;
            if(req != null)
            {
                var trans = requestContext.GetItem("transaction") as ITransaction;
                if (trans != null && trans.IsActive)
                    trans.Rollback();
    
                var session = requestContext.GetItem("session") as ISession;
                if (session != null)
                {
                    session.Flush();
                    session.Close();
                }
            }
            return base.HandleException(requestContext, request, ex);
        }        
    }   
    

提交回复
热议问题