我正在尝试使用Asp.Net Core为我的一个项目创建“支付网关”抽象,以便客户可以通过创建派生库来集成其支付网关。我的应用程序将加载派生的库并调用方法。
以下是所有支付网关必须实现的接口。这位于Core库中,我们称之为 PaymentGateway.Core.dll 。该库是主应用程序的一部分。
namespace PaymentGateway.Core
{
public interface IPaymentGateway
{
string Name { get; }
// The purpose of this function is to transform the order details into an object,
// as expected by the underlying gateway's apis
object CreatePaymentRequest(Order request);
// The purpose of this function is to transform the payment response object,
// received from the payment gateway api,
// into an application entity that represents this payment.
Payment ProcessPaymentResponse(object response);
}
// Order for which the payment to be collected. This entity is stored in DB
public class Order
{
string UserId { get; set; }
string ProductId { get; set; }
double OrderTotal { get; set; }
}
// A payment attempted for an Order. This entity is stored in DB
public class Payment
{
Order Order { get; set; }
string PaymentGateway { get; set; }
double Amount { get; set; }
PaymentStatus Status { get; set; } // Failed, User Aborted, Success
}
}
以下是PayPal集成库的示例,我们将其称为 PaymentGateway.PayPal.dll 。该库引用核心库并实现PaymentGateway接口。
namespace PaymentGateway.PayPal
{
class PayPal : IPaymentGateway
{
public string Name { get => "PayPal"; }
public object CreatePaymentRequest(Order request)
{
:
:
}
public Payment ProcessPaymentResponse(object response)
{
:
:
}
}
}
核心库中执行付款的流程如下:
我的问题是应用程序(Core)不了解CreatePaymentRequest()的返回类型,因为它取决于调用的网关。同样,对于ProcessPaymentResponse(),参数类型是特定于网关的,并且该类型将在网关库中定义。
现在我被迫使用System.Object。有什么更好的解决方案吗?
答案 0 :(得分:1)
public interface IPaymentGateway<T> where T : class
{
string Name { get; }
T CreatePaymentRequest(PaymentRequest request);
PaymentResponse ProcessPaymentResponse(T response);
}
public class PayPal<T> : IPaymentGateway<T> where T : class
{
public string Name { get; }
public T CreatePaymentRequest(PaymentRequest request)
{
throw new NotImplementedException();
}
public PaymentResponse ProcessPaymentResponse(T response)
{
throw new NotImplementedException();
}
}
public class Example
{
public void ExampleMethod()
{
IPaymentGateway<Foo> paypal = new PayPal<Foo>();
var name = paypal.Name;
Foo paymentRequest = paypal.CreatePaymentRequest(new PaymentRequest());
var paymentResponse = paypal.ProcessPaymentResponse(new Foo());
}
}
public class Foo
{
}
public class PaymentResponse
{
}
public class PaymentRequest
{
}
为什么不返回object
而不使它通用,并让它们传递类型?