Resolving a ServiceStack Service and defining cont

2019-08-08 20:32发布

问题:

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