2013-08-24 21 views
1

在我看到的所有示例like this中,ServiceStack方法中的緩存必須具有返回類型System.Object。是否有更新的/更新的文檔可以返回正常的DTO?使用ServiceStack + Redis進行緩存:如何不返回System.Object並返回DTO?

例如,如果此Get方法沒有返回「對象」(從ServiceStack文檔中提取),那將會更好。

public class OrdersService : Service 
{ 
    public object Get(CachedOrders request) 
    { 
     var cacheKey = "unique_key_for_this_request"; 
     return base.RequestContext.ToOptimizedResultUsingCache(base.Cache,cacheKey,()=> 
      { 
       //Delegate is executed if item doesn't exist in cache 
       //Any response DTO returned here will be cached automatically 
      }); 
    } 
} 
+0

在這一點上返回DTO有什麼好處? –

+0

它會更加明確一些,並且與其他服務方法返回具體類型一致。 – mariocatch

+0

公平 - 我並不認爲這是值得的,因爲返回類型由您的CachedOrders類型實現的IReturn <>接口指定。保持它作爲一個對象在其他方面提供了更大的靈活性,例如,如果你想返回一個HttpError。 –

回答

2

我使用這個擴展,但是失去了基於請求上下文的優化。 (json,壓縮等)

public static class ICacheClientExtensions 
{ 
    public static T ToResultUsingCache<T>(this ICacheClient cache, string cacheKey, Func<T> fn, int hours = 1) where T : class 
    { 
     var cacheResult = cache.Get<T>(cacheKey); 
     if (cacheResult != null) 
     { 
      return cacheResult; 
     } 
     var result = fn(); 
     if (result == null) return null; 
     cache.Set(cacheKey, result, TimeSpan.FromHours(hours)); 
     return result; 
    } 
} 

public class MyService : Service 
{ 
    public Data Get(GetData request) 
    { 
     var key = UrnId.Create<Data>(request.Id); 

     Func<Data> fn =() => Db.GetData(request.Id); 

     return Cache.ToResultUsingCache(key, fn); 
    } 

    [Route("/data/{id}")] 
    public class GetData: IReturn<Data> 
    { 
     public int Id{ get; set; } 
    } 
}