2013-07-09 53 views
1

所以我的問題圍繞在以下鏈接描述圍繞需要apphost.ResolveService: Calling a ServiceStack service from RazorServiceStack ResolveService

我在我的_Layout.cshtml

明明下面的代碼工作完美,但作爲建議答案在上面的網址,卻是有點傻

SMSGateway.Services.EntityCollectionResponse response = 
    new ServiceStack.ServiceClient.Web.JsonServiceClient(
     "http://localhost:1337/") 
     .Get<SMSGateway.Services.EntityCollectionResponse>(
      "/entities"); 

所以這給了我實體的名單:)但不是最佳的...所以這是我嘗試做正確的方式

var response = ConsoleAppHost.Instance 
    .ResolveService<SMSGateway.Services.EntityService>(
     HttpContext.Current).Get(
      new SMSGateway.Services.EntitiesRequest()); 

// SMSGateway.Services.EntityCollectionResponse response = 
//  base.Get<SMSGateway.Services.EntityService>().Get(
//   new SMSGateway.Services.EntitiesRequest()); 

foreach (var entity in response.Result) 
{ 
    <li> 
     <a href="@entity.MetaLink.Href"> 
      @Html.TitleCase(entity.Name) entities 
     </a> 
    </li> 
} 

好了,所以我得到的錯誤是:

錯誤CS0122:ConsoleAppHost是不可訪問,因爲它保護 水平....

這個預期?我在想,如果這不是我可能不被允許在_Layout.cshtml文件中調用這個的情況?

進一步閱讀使我的文章InternalVisibleTo Testing Internal Methods in .NET 2.0

,我發現很有趣的:P但是沒有雪茄:)

+0

我要尋找的東西,讓我用另一種「RenderBody」 ......因爲在_layout.cshtml除非我稱之爲「RenderBody」,否則我似乎無法從我的服務中獲取信息/模型,而且這樣做每個視圖只允許一個模型...因此,如何爲我的佈局提供不同的模型?這就是我選擇在Razor中使用JSONClient的原因.... –

回答

5

我建議您不要在剃刀模板呼叫服務。 Razor模板只能用於從模型中渲染某些標記。

實際數據訪問應該在提供此模板的ServiceStack服務中執行。所以你的情況,你可以打電話從操作的另一個服務:

public object Get(SomeRequestDto message) 
{ 
    var response = this 
     .ResolveService<SMSGateway.Services.EntityService>() 
     .Get(new SMSGateway.Services.EntitiesRequest() 
    ); 

    return response.Rersult; 
} 

,或者你可能會離開容器注入依賴服務到當前的服務,讓你甚至都不需要使用一些服務定位器反-patterns。

public SomeService: Service 
{ 
    private readonly EntityService entityService; 
    public SomeService(EntityService entityService) 
    { 
     this.entityService = entityService; 
    } 

    public object Get(SomeRequestDto message) 
    { 
     var response = this.entityService.Get(new SMSGateway.Services.EntitiesRequest() 

     return response.Rersult; 
    } 
} 

,然後當然你的Razor視圖意願強類型的對應型號:

@model IEnumerable<WhateverTheTypeOfTheResultYouWannaBeLoopingThrough> 
foreach (var entity in Model) 
{ 
    <li> 
     <a href="@entity.MetaLink.Href"> 
      @Html.TitleCase(entity.Name) entities 
     </a> 
    </li> 
}