我创建了一个服务,允许我利用 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/