ServiceStack ResolveService

Jac*_*oos 1 inversion-of-control dto razor servicestack

所以我的问题围绕调用以下url中描述的apphost.ResolveService: 从Razor调用ServiceStack服务

我在_Layout.cshtml中

显然下面的代码工作得很好,但正如上面的url中的答案所示,它有点愚蠢

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

所以这给了我一个实体列表:)但不是最优的...所以这是我尝试以正确的方式做到这一点

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>
}
Run Code Online (Sandbox Code Playgroud)

好的,我得到的错误如下:

错误CS0122:由于其保护级别,ConsoleAppHost无法访问....

这是预期的吗?我在考虑是否这不是我可能不允许在_Layout.cshtml文件中调用它的情况?

进一步阅读带我进入了.NET 2.0中的InternalVisibleTo Testing Internal Methods文章

我觉得非常有趣:P但没有雪茄:)

Dar*_*rov 5

我建议你不要在Razor模板中调用服务.Razor模板应仅用于从模型中呈现某些标记.

应该在呈现此模板的ServiceStack服务中执行实际的数据访问.因此,在您的情况下,您可以从操作中调用另一个服务:

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

    return response.Rersult;
}
Run Code Online (Sandbox Code Playgroud)

或者您可以离开容器以将依赖服务注入当前服务,这样您甚至不需要使用某些服务定位器反模式.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你的Razor视图当然会强烈输入相应的模型:

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