c# - Stripe.Net 类的依赖注入(inject)

标签 c# .net-core stripe-payments

我创建了一个服务,允许我利用 Stripe.Net 类(我将其称为处理程序),但它并不是真正可测试的,因为在方法中我会实例化该类。例如:

public Customer CreateCustomer(string email)
{
    var service = new CustomerService();

    return service.Create(new CustomerCreateOptions
    {
        Email = email
    });
}

这在尝试创建测试时非常有用。所以我想我可以只使用 Stripe.net 中的类而不是创建处理程序。所以我尝试这样做:

private static void AddTransients(IServiceCollection services)
{
    services.AddTransient<Service<IStripeEntity>>();
    services.AddTransient<ICreatable<IStripeEntity, BaseOptions>>();, BaseOptions));
}

通过它,我可以像任何其他注入(inject)的类一样在 Controller 周围传递类。但是当我启动我的应用程序时,我收到此错误:

Cannot instantiate implementation type 'Stripe.IStripeEntity' for service type 'Stripe.IStripeEntity'.

所以我尝试将这些类注册为通用类,如下所示:

private static void AddTransients(IServiceCollection services)
{
    services.AddTransient(typeof(Service<>));
    services.AddTransient(typeof(ICreatable<,>));
}

但是当我运行它时,我得到了同样的错误。有谁知道我能做些什么来让它发挥作用?

最佳答案

我通过创建包装类解决了这个问题。不是最理想的,但它有效:

public class StripeCustomerService : IStripeCustomerService
{
    private readonly CustomerService _customerService;
    public StripeCustomerService() => _customerService = new CustomerService();

    public Customer Create(string email)
    {
        return _customerService.Create(new CustomerCreateOptions
        {
            Email = email
        });
    }

    public async Task<Customer> GetAsync(string id, CancellationToken cancellationToken) =>
        await _customerService.GetAsync(id, cancellationToken: cancellationToken);
}

关于c# - Stripe.Net 类的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62119536/

相关文章:

c# - int.MinValue 和 int.MaxValue 之间的随机数,包括

c# - 在 .NET 中命名电子邮件附件的正确方法是什么?

c# - 'T' 不包含 'Foo' 的定义,最佳扩展方法重载需要类型为 'IType' 的接收器

stripe-payments - 如何使用 curl 和 Stripe 检查客户是否订阅了

stripe-payments - Stripe 在每次数量更新时立即付款

c# - 打开刚刚关闭的文件

javascript - 使用 Ajax 向 Controller 发送 post 请求时的 Model 与 List<Model>

asp.net-core - 为什么默认的 mvc6 模板针对多个 DNX 版本?

c# - 使用 Azure 服务总线发送消息时身份验证失败

stripe-payments - 如何知道 stripe connect 连接的用户登录流程是否已完成或者是否需要更多信息?