解决ServiceStack服务并定义内容类型 [英] Resolving a ServiceStack Service and defining content type

查看:220
本文介绍了解决ServiceStack服务并定义内容类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发C#ServiceStack API.

I'm currently developing a C# ServiceStack API.

在其中一项服务中,我需要执行另一项服务.我从Funq容器解析服务并执行相关方法,但返回的是json而不是.net对象.

In one of the Services I need to execute another service. I resolve the service from the Funq container and execute the relevant method but get json returned instead of .net objects.

我理解这是因为前端发出的原始请求是针对json的内容类型,而默认内容类型是json.

I understand this is because the original request from the front end was for a content-type of json and the default content type is json.

有没有一种方法可以解析服务并执行其方法,但是可以接收.net对象?

Is there a way I can resolve the service and execute its methods but receive .net objects instead?

推荐答案

您可以使用ResolveService<T>执行并委托给ServiceStack中的另一个服务,例如:

You can execute and delegate to another Service in ServiceStack by using ResolveService<T>, e.g:

从ServiceStack服务内部:

From inside a ServiceStack Service:

using (var service = base.ResolveService<MyService>())
{
    var response = service.Get(new MyRequest { ... });
}

在自定义用户会话中:

using (var service = authService.ResolveService<MyService>())
{
    var response = service.Get(new MyRequest { ... });
}

从ServiceStack外部:

From outside of ServiceStack:

using (var service = HostContext.ResolveService<MyService>())
{
    var response = service.Get(new MyRequest { ... });
}

ServiceStack服务只是普通的依赖项

由于ServiceStack中的服务与任何其他IOC依赖项一样,因此 ResolveService 只是从ServiceStack的IOC解析服务并注入当前请求,即:

ServiceStack Services are just normal Dependencies

Since Services in ServiceStack are just like any other IOC dependency, the implementation of ResolveService simply resolves the Service from ServiceStack's IOC and injects the current Request, i.e:

public static T ResolveService<T>(HttpContextBase httpCtx=null) 
    where T : class, IRequiresRequest
{
    var service = AssertAppHost().Container.Resolve<T>();
    if (service == null) return null;
    service.Request = httpCtx != null 
        ? httpCtx.ToRequest() 
        : HttpContext.Current.ToRequest();
    return service;
}

这篇关于解决ServiceStack服务并定义内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆