cecilphillip-stripe / stripe-dotnet-extensions

MIT License
5 stars 0 forks source link

Stripe Assembly Scanning #2

Closed cecilphillip-stripe closed 9 months ago

cecilphillip-stripe commented 2 years ago

@pakrym-stripe what are your thoughts on using something like this to register all the Stripe services

This ends up registering about 100+ of our services. I'm wondering if we need to register all of those up front or maybe we can use source generation? 🤔

var collection = new ServiceCollection();

var serviceProvider = FromAssembly(collection).BuildServiceProvider();
var productService = serviceProvider.GetRequiredService<ProductService>();

static IServiceCollection FromAssembly(IServiceCollection collection)
{
    var types = typeof(StripeClient).Assembly.DefinedTypes.Select(x => x.AsType())
        .Where(t => t.IsClass && !t.IsAbstract && t.IsPublic && t.Name.EndsWith("Service"));

    foreach (var type in types)
    {
        TryAddType(collection, type);
    }

    return collection;
}

static void TryAddType(IServiceCollection collection, Type type)
{
    ConstructorInfo[] constructorInfo = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
    foreach (var constructr in constructorInfo)
    {
        var parameters = constructr.GetParameters();
        foreach (var parametr in parameters)
        {
            if (parametr.ParameterType == typeof(IStripeClient))
            {
                collection.TryAdd(ServiceDescriptor.Transient(type, type));
                return;
            }
        }
    }
}
pakrym-stripe commented 2 years ago

@pakrym-stripe what are your thoughts on using something like this to register all the Stripe services

I usually prefer explicit registrations but this should be fine. If we have any problems we can move to source-generation.

ServiceDescriptor.Transient(type, type))

SHould this be singleton?

cecilphillip-stripe commented 2 years ago

@pakrym-stripe No, because the HttpClient the constructor receives would ended up being captured as a Singleton and then defeat the purpose of using the HttpClientFactory

pakrym-stripe commented 2 years ago

I wonder if it would, the HttpClientFactory itself is registered as singleton (https://github.com/dotnet/runtime/blob/main/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientFactoryServiceCollectionExtensions.cs#L35) and the HttpClient instances all use the same set of pooled handlers.

cecilphillip-stripe commented 9 months ago

we're going with source generators #7