Hector
Hector

Reputation: 1220

Calling ServiceStack internally with URL & JSON

I have log data consisting of the original request body JSON and path it was received on. When a certain service is triggered I in effect want to run this.

Ie for each url/json object in the log I want to resolve the service and have it handle the request. The API is large and growing so I don't want to have to manually wire up each call.

Is there a way to do this internally? Ie without sending new requests out on the loopback?

Thanks,

Hector

Upvotes: 0

Views: 756

Answers (2)

Scott
Scott

Reputation: 21521

It is possible to do using ServiceStack's BasicRequest which can be plugged into the ServiceStack request pipeline using the HostContext.ServiceController.Execute method.

Note this method does not trigger the filters or dependancy injection (You can still resolve from the container in your action method). So this is essentially the same behaviour as MQ requests. So if your requests require to use filters etc, this method of direct service execution may not be suitable for you.

What this does do:

  • Parses the provided URL to identify the request DTO type
  • Resolves the Service responsible for handling the DTO
  • Calls the action method passing in the DTO
  • Returns the result from the DTO

Use this method to process the request:

static object CallInternalService(string path, string method = "GET", string jsonData = null)
{
    // Determine the request dto type based on the rest path
    var restPath = HostContext.ServiceController.GetRestPathForRequest(method, path);
    if(restPath == null || restPath.RequestType == null)
        throw new Exception("No route matched the request"); // Note no fallbacks

    // Create an instance of the dto
    var dto = Activator.CreateInstance(restPath.RequestType);
    if(jsonData != null)
    {
        var data = ServiceStack.Text.JsonSerializer.DeserializeFromString(jsonData, restPath.RequestType);
        dto.PopulateWith(data);
    }

    // Create a basic request
    var request = new BasicRequest(dto, RequestAttributes.None);

    // Execute the request
    return HostContext.ServiceController.Execute(dto, request);
}

So you simply pass the URL /Someaction/value and the method POST, along with the JSON data payload:

var result = CallInternalService("/users/123", "POST", "{\"Name\":\"Bob\",\"Age\":28}");

I hope that helps.

Upvotes: 3

jacksonakj
jacksonakj

Reputation: 882

For one-way messages the Messaging API is your best option. At the moment there isn't any inter process communication option, such as, named pipes. However, I did submit a feature request for named pipes.

Upvotes: 0

Related Questions