Resolving a ServiceStack Service and defining content type

六眼飞鱼酱① 提交于 2019-12-13 00:09:28

问题


I'm currently developing a C# ServiceStack API.

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.

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.

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


回答1:


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

From inside a ServiceStack Service:

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

From inside a custom user session:

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

From outside of ServiceStack:

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

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;
}


来源:https://stackoverflow.com/questions/23808979/resolving-a-servicestack-service-and-defining-content-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!