Executing a Service Internally

I have a method that I want to be able to either execute via an API call or by calling it ‘internally’ from code.

What is the preferred method of doing this? I had looked at using Gateway.Send, which I thought was the preferred way of doing this, however I get an “object not referenced” exception, which suggests that I need to set up the Gateway before calling it (?)

ServiceStack.Instance.Execute does what I need but I want to make sure that my ServiceStack is properly idiomatic.

The calling method:

public void Process()
{
    CompanyCodes
       .Each(code =>
       {
           //Gateway.Send(new ProcessUnsentEmailsRequest {CompanyCode = code}); 
           ServiceStack.Instance.ExecuteService(new ProcessUnsentEmailsRequest {CompanyCode = code});
       });
}

The DTO:

public class ProcessUnsentEmailsRequest : IReturnVoid
{
    public string CompanyCode { get; set; }
}

The service method:

public void Any(ProcessUnsentEmailsRequest request)
{
    //....
}

You shouldn’t need to do anything to setup the Gateway as it should default to executing in-process Services. But where are you accessing the Gateway dependency from, inside another Service? and has the AppHost been initialized?

Outside of the Service you should be using the HostContext.AppHost.GetServiceGateway(IRequest) gateway APIs, otherwise you can also resolve the Service manually from the IOC and execute it with:

using (var service = HostContext.ResolveService<MyProcessService>(req)
{
    service.Any(new ProcessUnsentEmailsRequest {CompanyCode = code});
}

Ideally you’d pass in a ServiceStack IRequest but if you’re in the context of HTTP Request in ASP.NET you can create a new IRequest from the current HTTP Request otherwise you’d need to fallback to an empty BasicRequest, e.g:

var req = HostContext.TryGetCurrentRequest() ?? new BasicRequest();

I’m not entirely sure what I did wrong. However, since I am trying to call the service from an ordinary C# class I get what I need from using the following code:

using (var notifications = HostContext.ResolveService<NotificationService>(new BasicRequest()))
{
    notifications.Any(new ProcessUnsentEmailsRequest {CompanyCode = code});
}

Thank you.