Skip to content

Instantly share code, notes, and snippets.

@JKamsker
Created August 17, 2023 14:32
Show Gist options
  • Save JKamsker/1d833023471b8cff239bda41f08d3eec to your computer and use it in GitHub Desktop.
Save JKamsker/1d833023471b8cff239bda41f08d3eec to your computer and use it in GitHub Desktop.
Constructor Redirect

Proposal: Constructor redirect

Summary: Allow for constructor arguments to be seemingly mirrored by a generic factory method.

Sample: myfactory.Create("param1", "param2", "param3");

class CommandType
{
    
    public CommandType(string param1, string param2, string param3, [FromServices]DbContext context)
    {
        // do something
    }
}

class MyFactory
{
    private readonly IServiceProvider _provider;
    public MyFactory(IServiceProvider provider)
    {
        _provider = provider;    
    }

    [RelayArguments]
    public T Create<T>(params object[] args)
    {
        return ActivatorUtilities.CreateInstance<T>(_provider, args);
    }
}

Alternatives: - Source Generators: a source generator could be written to archive this goal, but source generators do not fully support method signature changes. (They do support it but visual studio does not update the generated code when the signature changes) - Generic Factory: a generic factory could be written (sample below) but this would require the developer to know the constructor parameters of the type they are trying to create. ```csharp class MyFactory { private readonly IServiceProvider _provider; public MyFactory(IServiceProvider provider) { _provider = provider;
}

        public T Create<T>(params object[] args)
        {
            return (T)ActivatorUtilities.CreateInstance(_provider, typeof(T), args);
        }
    }
    ```
- Manually Implementing the factory for each type:
    this is the current solution, but it requires a lot of boilerplate code to be written for each type that needs to be created.

Motivation: Having a factory method that can create instances of a type is already possible. Now, with intellisense support, it would be possible to create instances of a type without having to know the constructor parameters.

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