Skip to content

[API Proposal]: ActivatorUtilities.CreateFactory<T> with params span #101889

Open

Description

Background and motivation

The arguments passed to CreateFactory and ObjectFactory are usually of a fixed number so it may be worthwhile to consider params span for both instead of array.

API Proposal

I haven't seen an addition like this so far so I'm not sure about the naming convention.

namespace Microsoft.Extensions.DependencyInjection
{
  public delegate T ObjectFactoryWithParams<out T>(IServiceProvider serviceProvider, params ReadOnlySpan<object?> arguments); 

  public static class ActivatorUtilities
  {
    public static ObjectFactoryWithParams<T> CreateFactory2<T>(params ReadOnlySpan<Type> argumentTypes)
  }
}

API Usage

var factory = ActivatorUtilities.CreateFactory<T>(typeof(SomeType));
var result = factory(serviceProvider, new SomeType());

Alternative Designs

An alternative is to consider making the return type a generic delegate over argument types.

public static ObjectFactory<TArg1, T> CreateFactory<T, TArg1>();
public static ObjectFactory<TArg1, TArg2, T> CreateFactory<T, TArg1, TArg2>();
// etc
public delegate T ObjectFactory<in TArg1, out T>(IServiceProvider serviceProvider, TArg1? arg1);
public delegate T ObjectFactory<in TArg1, in TArg2, out T>(IServiceProvider serviceProvider, TArg1? arg1, TArg2? arg2);
// etc
var factory = ActivatorUtilities.CreateFactory<T, SomeType>();
var result = factory(serviceProvider, new SomeType());

Risks

No response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions