2011-11-21 18 views
0

我试图在活动记录中为每个WCF请求设置一个会话。下面是代码:如何在WCF中设置活动记录会话

[WebGet(UriTemplate = "ReadMessages?authUserId={authUserId}&authGuid={authGuid}&userId={userId}&lastMessageId={lastMessageId}&startDate={startDate}&endDate={endDate}")] 
     public IQueryable<Message> ReadMessages(int authUserId, string authGuid, uint userId, uint lastMessageId, 
      DateTime startDate, DateTime endDate) 
     { 
      UserUtility.Authenticate(authUserId, authGuid); 

      using (new SessionScope()) 
      { 
       //get messages. 
       return from m in MessageData.FindAll(userId, lastMessageId, startDate, endDate) 
        select ConvertToView(m); 
      } 
     } 

即使我有SessionScope使用块,但它仍然给了我一个延迟加载错误,因为它返回一个IQueryable所以它转换成一个视图,这将触发延迟加载,它出来后我正在猜测使用的块。这是错误:

正在初始化[xxx.Business.Schemas.CommonSchemas.Models.Messaging.Message#6575] - 无法长期初始化角色集合:xxx.Business.Schemas.CommonSchemas.Models.Messaging.Message .MessageStatusHistories,没有会话或会话关闭

在我的配置中,我有IsRunningWebApp为true。

var source = new InPlaceConfigurationSource(); 
source.IsRunningInWebApp = true; 

如果你想知道为什么我从一个WCF Web方法返回IQueryable的,那是因为我使用的是WCF的Web API(http://wcf.codeplex.com/wikipage?title=WCF %20HTTP),它允许你使用ODATA在URL查询字符串中查询你的对象。

我在做什么错?我如何创建一个持续时间足够延迟加载模型的会话,因为我将它们转换为从Web方法返回的视图?

回答

0

我最终得到它的工作在我的Global.asax使用此:

public void Application_BeginRequest(object sender, EventArgs e) 
     { 
      HttpContext.Current.Items.Add("ar.sessionscope", new SessionScope()); 
     } 

     public void Application_EndRequest(object sender, EventArgs e) 
     { 
      try 
      { 
       var scope = HttpContext.Current.Items["ar.sessionscope"] as SessionScope; 
       if (scope != null) 
        scope.Dispose(); 
      } 
      catch (Exception ex) 
      { 
       HttpContext.Current.Trace.Warn("Error", "EndRequest: " + ex.Message, ex); 
      } 
     } 

注:我也不得不删除使用(新SessionScope())从Web方法,将与干扰解决方案