我要求让一个服务处理请求,将其转换为其他请求,将该请求传递给内部服务,获取响应,然后将其转换回外部服务响应.有些代码可能会更好地解释它.这就是我所做的:
public class InviteUserService : Service, IPost<Invitee>
{
public RegistrationService RegistrationService { get; set; }
public object Post(Invitee invitee)
{
// Do other invitation related work that is part of my domain.
var registration = invitee.TranslateTo<Registration>();
registration.UserName = invitee.EmailAddress;
registration.Email = invitee.EmailAddress;
// It previously threw a null ref exception until I added this.
RegistrationService.RequestContext = RequestContext;
var response = RegistrationService.Post(registration);
if (response is RegistrationResponse)
{
var inviteeResponse = response.TranslateTo<InviteeResponse>();
return inviteeResponse;
}
// Else it is probably an error and just return it directly to be handled by SS.
return response;
}
}
Run Code Online (Sandbox Code Playgroud)
正如上面代码中的注释所示,在我传递之前,RequestContext
它失败并出现NullReferenceException.既然我已经做到了它确实有效,但是我想知道我是否正在进入关于ServiceStack如何工作的上游战斗?它会在赛道上引起更多问题吗?
如果两个服务都在我的控制之下,我只需将注册代码移动到一个单独的共享依赖项中.但是RegistrationService
内置于ServiceStack中,除此之外似乎不能以任何其他方式调用.除非我错过了什么?
将请求委托给ServiceStack中的其他服务的方法是调用base.ResolveService<T>
哪个只是从IOC解析服务并为您注入当前的RequestContext.这与您正在进行的操作基本类似,但由于这是执行此操作的官方API,因此如果需要执行任何其他操作,则会进行维护.
使用此API,您的服务将如下所示:
public class InviteUserService : Service, IPost<Invitee>
{
public object Post(Invitee invitee)
{
// Do other invitation related work that is part of my domain.
var registration = invitee.TranslateTo<Registration>();
registration.UserName = invitee.EmailAddress;
registration.Email = invitee.EmailAddress;
// Resolve auto-wired RegistrationService from IOC
using (var regService = base.ResolveService<RegistrationService>())
{
var response = regService.Post(registration);
if (response is RegistrationResponse)
{
var inviteeResponse = response.TranslateTo<InviteeResponse>();
return inviteeResponse;
}
return response;
}
}
}
Run Code Online (Sandbox Code Playgroud)