This project provides Roslyn code refactoring, which automatically adds Add(Singleton|Scoped|Transient) inferred from your class declaration into nearest DI registration method.
It could be default ConfigureServices in Startup.cs, or your custom extension method.
Assumptions made
You use Microsoft.Extensions.DependencyInjection to register services
You use default ConfigureServices in Startup.cs and/or custom extension methods (Registration Method) to register services with following signature:
public static class Module
{
public static IServiceCollection RegisterServices(this IServiceCollection services)
{
return services.AddSingleton<Foo>()
...
;
}
}
You want to modularize and split your registration method into multiple files, and keep them closer to classes which they register OR you just want to reduce number of keystrokes you need to register class in DI container
You don't want to use tools like Scrutor for automated assembly scanning
Then this code refactoring can make your life a little bit easier, generating registration method call for you 🙂
Features
Code Actions with AddSingleton|AddScoped|AddTransient methods with appropriate type parameters will be inferred from your class declaration
Exact signature of AddX will be inferred from position, where refactoring was triggered:
If it was triggered on class name itself, then refactoring will register it as AddX<ClassName>
If it was triggered on a base type or an interface of a class, then refactoring will register it as AddX<BaseType, ClassName>
Refactoring will add registration into nearest registration method using one of two heuristics:
If registration method body is empty or it does not contains chain calls with length greater than 1, then registration will be added onto first line with separate statement services.AddX<IFoo, Foo>();
If Registration Method contains call chain of length greater than 1, then registration will be appended to that call chain
You can annotate method which follows convention, but you don't want to be considered as registration method with [IgnoreRegistrationMethod] attribute
You can annotate method which does not follow convention, but you want it to be considered as registration method with [RegistrationMethod] attribute
Adds using to registration method's file, if it's required
Installation
It can be installed in any project through nuget package . It works with Rider 2021.3 and Visual Studio 2022.
To install it in all projects for a given solution, create Directory.Build.props file with following content: