Welcome to the T4 C# Constructor Generator project
T4 C# Constructor Generator is a T4 template for Visual Studio C# projects that lowers the overhead of the C# compiler by generating constructors.
Overview
The
SOLID principles advocate small and focused classes, and
Dependency Injection advocates injecting all a classes dependencies through the constructor. Especially when classes are small, defining a constructor that does nothing more than the proper null-checks and assigning the constructor parameters to the private fields gives a lot of overhead. It's verbose and it's just noise.
This template tries to lower this overhead and verbosity by searching through all classes in the project and generating a constructor for classes that don't have any constructor defined. You can see it as a change of the behavior of the C# compiler. The C# compiler always generates a public parameterless constructor when no constructor is defined, but this template changes this by generating a constructor that contains all defined private fields of that class.
Example
Take a look at the following class:
public class UserController : Controller
{
private readonly IRepository<User> userRepository;
private readonly ILogger logger;
private readonly ICommandHandler<MoveCustomerCommand> handler;
public View Index()
{
}
}
The
T4 C# Constructor Generator template will generate a new partial class with the following constructor:
public UserController(IRepository<User> userRepository, ILogger logger,
ICommandHandler<MoveCustomerCommand> handler)
{
if (userRepository == null) throw new ArgumentNullException("userRepository");
if (logger == null) throw new ArgumentNullException("logger");
if (handler == null) throw new ArgumentNullException("handler");
this.userRepository = userRepository;
this.logger = logger;
this.handler = handler;
this.OnCreated();
}
Constraints
This template can only handle C# projects and will only generate constructors for classes that:
- Are in the same project as where the template is placed:
- Are not static:
- Have no explicitly defined constructors:
- Have private instance fields;
If you find any bugs of have any feature requests, please report them
here.