首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Stripe.Net类的依赖注入

Stripe.Net类的依赖注入
EN

Stack Overflow用户
提问于 2020-05-31 16:52:43
回答 1查看 588关注 0票数 2

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

代码语言:javascript
复制
public Customer CreateCustomer(string email)
{
    var service = new CustomerService();

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

这是很好的尝试创建一个测试。因此,我想我可以只使用Stripe.net中的类,而不是创建处理程序。所以我试过这样做:

代码语言:javascript
复制
private static void AddTransients(IServiceCollection services)
{
    services.AddTransient<Service<IStripeEntity>>();
    services.AddTransient<ICreatable<IStripeEntity, BaseOptions>>();, BaseOptions));
}

这样我就可以像其他注入类一样通过控制器周围的类。但是,当我启动我的应用程序时,我会得到以下错误:

无法为服务类型'Stripe.IStripeEntity‘实例化实现类型'Stripe.IStripeEntity’。

因此,我尝试将这些类注册为泛型类,如下所示:

代码语言:javascript
复制
private static void AddTransients(IServiceCollection services)
{
    services.AddTransient(typeof(Service<>));
    services.AddTransient(typeof(ICreatable<,>));
}

但是当我运行它时,我会得到同样的错误。有人知道我能怎么做才能让这件事奏效吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-31 18:22:54

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

代码语言:javascript
复制
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);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62119536

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档