Tolitech.DependencyInjection.Generators is a C# source generator that automates the registration of services in the dependency injection container. It scans for interfaces annotated with the [ServiceRegistration] attribute and generates code to register their implementations with the specified lifetime (Singleton, Scoped, Transient).
- Automatic registration of services based on interface attributes
- Supports Singleton, Scoped, and Transient lifetimes
- Generates extension method
AddGeneratedServicesforIServiceCollection - Reduces boilerplate and manual DI configuration
To use the library, download the package via NuGet:
dotnet add package Tolitech.DependencyInjection.GeneratorsUse the ServiceRegistrationAttribute to annotate your interfaces:
using Tolitech.DependencyInjection.Generators.Abstractions;
using Microsoft.Extensions.DependencyInjection;
[ServiceRegistration(ServiceLifetime.Transient)]
public interface IService {}
[ServiceRegistration(ServiceLifetime.Scoped)]
public interface IRepository {}Create concrete classes implementing your annotated interfaces:
public class Service : IService {}
public class Repository : IRepository {}Call the generated extension method in your DI setup:
var services = new ServiceCollection();
services.AddGeneratedServices();All implementations will be registered with the correct lifetimes.
[ServiceRegistration(ServiceLifetime.Singleton)]
public interface IMyService {}
public class MyService : IMyService {}
// Registration
services.AddGeneratedServices();- The generator scans for interfaces with
[ServiceRegistration]. - It finds all implementations and registers them in DI.
- The generated code is added as an extension method to
IServiceCollection.
- .NET Standard 2.0+
- Microsoft.CodeAnalysis.CSharp
Generator.cs: Source generator logicServiceInfo.cs: Internal model for service registration
- Tolitech.DependencyInjection.Generators.Abstractions