【问题标题】:Dependency injection for Stripe.Net classesStripe.Net 类的依赖注入
【发布时间】:2020-09-19 00:07:21
【问题描述】:

我创建了一个允许我使用 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));
}

我通过这将允许我像任何其他注入类一样在我的控制器周围传递类。但是当我启动我的应用程序时,我收到了这个错误:

无法为服务类型“Stripe.IStripeEntity”实例化实现类型“Stripe.IStripeEntity”。

所以我尝试像这样将类注册为通用类:

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

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

【问题讨论】:

    标签: c# .net-core stripe-payments


    【解决方案1】:

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

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

    【讨论】:

    • 这可行,但这不会使它无法测试吗?
    • 你可以改变签名注入 CustomerService 然后它就可以测试了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 2016-06-22
    • 2021-09-11
    • 2012-01-03
    • 2018-06-29
    • 1970-01-01
    相关资源
    最近更新 更多