How to pass variables between Services?

I am wondering what the best way is to execute another service from within a service?
I use

var output = (HttpResult) await ServiceStackHost.Instance.ExecuteServiceAsync(input, this.Request);

where input is my dto -> I return always an HttpResult for your reference.

This works OK, but sometimes I need to pass a reference of for example my IDbConnection to use the same transaction for example.

Is there a clean way to call a service for another dto within a service and pass variables?
Thx.

I would never bleed a transaction across service boundaries, refactor it to create a new Service that does the composite behavior you need then push any shared logic that different services share in a reusable dependency (or Extension method if the logic doesn’t need additional deps).

Ultimately the Service Gateway is the recommended way to call Services, an alternative approach is to use ResolveService where since you retrieve an instance of your Service class you can populate deps directly, e.g. if you add a UseDb property to your Services:

public IDbConnection UseDb { set => db = value; }

You can populate it with:

using (var myService = base.ResolveService<MyService>())
{
    myService.UseDb = Db;
    var response = myService.Any(new MyRequest());
}

Otherwise the recommended way to pass anything between filters/services/etc is to use IRequest.Items which effectively everything has access to:

Request.Items["UseDb"] = Db;

...
var db = Request.Items["UseDb"] as IDbConnection;

Ok thanks @mythz for this insight!
Refactoring seems the best choice indeed, but all other options are valid in some cases.
:thumbsup:

1 Like