4

I have a requirement to have one service handle a request, transform it to some other request, pass that request to the inner service, get the response, and transform it back to the outer service response. Some code may explain it better. This is what I have done:

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;
    }
}

As the comment in the code above shows, before I passed down the RequestContext it was failing with a NullReferenceException. Now that I have done that it does work, but I'm wondering if I'm heading into an upstream battle in regards to how ServiceStack works? Will it cause me more problems down the track?

If both services were under my control, I would simply move the registration code into a separate shared dependency. However RegistrationService is built into ServiceStack, and doesn't seem to be callable in any other way apart from this. Unless I am missing something?

4

1 回答 1

5

将请求委托给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;
        }    
    }
}
于 2012-12-04T19:26:18.167 回答