我创建了一个服务,允许我利用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<,>));
}但是当我运行它时,我会得到同样的错误。有人知道我能怎么做才能让这件事奏效吗?
发布于 2020-05-31 18:22:54
我通过创建包装类来解决这个问题。不是最理想的,但它有效:
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);
}https://stackoverflow.com/questions/62119536
复制相似问题