多个服务处理一个请求类型

Multiple services handling a request type

为了解耦架构,我需要使用相同的请求 dto 调用不同的服务。

例如

// A value type has a callback url that will validate the request
public class ValueType {
    public string Id {get;set;}
    public string CallbackUrl {get;set;}
}

// The request dto to validate a value
public class ValidateRequest : IReturn<ValidateResponse>{
   public string ValueTypeId {get;set;}
   public string Value {get;set;}
}

// The validation response
public class ValidateResponse {
   public bool IsValid {get;set;}
}

我希望能够在多个服务中处理这些:

public class Service1 : Service {
    public object Get(ValidateRequest input){
        return new ValidateResponse(input.Value === "ABC")
    }
}

public class Service2 : Service {
    public object Get(ValidateRequest input){
        return new ValidateResponse(input.Value === "DEF")
    }
}

验证调用将在另一个服务中提交:

public class AnotherService : Service{

public object Post(ARequest input){

    var valueType = _valueTypeRepo.Get(input.type);
    var callbackUrl = valueType.callbackUrl;
    // callbackUrl = '/api/service1/validate' or '/api/service2/validate'
    // Here, I want to call either Service1 or Service2 based on runtime condition
    var jsonClient= new JsonClient(callbackUrl);
    jsonClient.Get(new ValidateRequest())...

}

}

如何注册多个路由来处理这个问题?

在这里,InvoiceService "knows" 关于 CustomerService。但是 CustomerService 不依赖 "InvoiceService"。这就是我所说的解耦架构的意思。多个服务可以添加自定义字段(甚至用户可以添加自定义字段,验证 url 完全是外部 API),而 "CustomerService" 不必依赖它们。

只有一个 Service class 可以提供请求 DTO 的实现,如果您需要它在不同的文件中,您可以使用部分 classes。它们也只能是请求 DTO 的单一实现,每个实现 can have multiple routes.

如果您绝对需要,您可以让其他请求 DTO 从同一个请求 DTO 继承,但作为 they’re already declarative I would avoid inheritance,如果您希望它们能够共享相同的验证逻辑,只需让它们实现相同的接口.

我对你试图通过运行时 proxy/delegation 实现实现的目标感到有点困惑,但如果你想调用另一个服务,请使用 Service Gateway instead of a Service Client which saves the overhead of a HTTP Service call for internal Services. If you need to convert a Request DTO with shared properties into a different Request DTO you can use ServiceStack's built-in Auto Mapping,这样你就可以将将 DTO 请求到具有共享属性的不同请求 DTO 并调用其服务:

var response = Gateway.Send(request.ConvertTo<MyRequest2>());