Best way to inject Gateway into non service classes?

I have some non server workflow management classes - would you have a recommended approach. I have created a single wrapper around the hostcontext which abstracts TryGetRequest and then GetServiceGateway based on this but not sure this is the right way to go.

Or should I refactor everything that needs Gateway/Request access into service classes and keep other dependencies purely for logic?

Dan

If you’re unsure how to resolve a Service dependency you can look at how the Service class does it, i.e:

private IServiceGateway gateway;
public virtual IServiceGateway Gateway => gateway ?? 
    (gateway = HostContext.AppHost.GetServiceGateway(Request));

Basically you’ll need access to the current IRequest and resolve it from AppHost.GetServiceGateway(Request).

You can use HostContext.TryGetRequest() to resolve an IRequest but that only works in ASP.NET Hosts so I’d advise against it.

For any dependencies that require access to the current IRequest (which is only available during the scope of a Current Request) I recommend passing it in as a param to the dependency, e.g:

public class MyServices : Service
{
    public IMyDep MyDep { get; set; }

    public object Any(MyRequest request) => MyDep.MyMethod(Gateway, request.Arg);
}

Ok cool - I’ve re-factored some of the code and it work better like this. You say you advise against HostContext.TryGetRequest() would you also advise against the HostContext.AppHost.GetServiceGateway singleton whe used in combined with the parameter passed IRequest?

Thanks for you help again.

Yep any API that passes in the IRequest is safe to use anywhere, e.g. inside or outside ServiceStack.