Dependency injection for Stripe.Net classes

Viewed 525

I created a service that allowed me to utilize the Stripe.Net classes (I called it a handler) but it wasn't really testable because in the methods I would instantiate the class. For example:

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

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

which it's great when trying to create a test. So I figured I could just use the classes in Stripe.net instead of creating a handler. So I have tried doing this:

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

Which I through would allow me to pass the classes around my controllers like any other injected class. But when I launch my application I get this error:

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

So I tried registering the classes as generic like this:

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

But when I run that, I get the same error. Does anyone know what I can do to get this to work?

1 Answers

I solved it by creating wrapper classes. Not the most ideal, but it works:

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