Skip to content

Tolitech/Tolitech.DependencyInjection.Generators

Repository files navigation

Tolitech.DependencyInjection.Generators

Overview

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).

Features

  • Automatic registration of services based on interface attributes
  • Supports Singleton, Scoped, and Transient lifetimes
  • Generates extension method AddGeneratedServices for IServiceCollection
  • Reduces boilerplate and manual DI configuration

Getting Started

Installation

To use the library, download the package via NuGet:

dotnet add package Tolitech.DependencyInjection.Generators

1. Annotate Interfaces

Use 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 {}

2. Implement Interfaces

Create concrete classes implementing your annotated interfaces:

public class Service : IService {}
public class Repository : IRepository {}

3. Register Services

Call the generated extension method in your DI setup:

var services = new ServiceCollection();
services.AddGeneratedServices();

All implementations will be registered with the correct lifetimes.

Example

[ServiceRegistration(ServiceLifetime.Singleton)]
public interface IMyService {}

public class MyService : IMyService {}

// Registration
services.AddGeneratedServices();

How It Works

  • 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.

Requirements

  • .NET Standard 2.0+
  • Microsoft.CodeAnalysis.CSharp

Project Structure

  • Generator.cs: Source generator logic
  • ServiceInfo.cs: Internal model for service registration

See Also

  • Tolitech.DependencyInjection.Generators.Abstractions

About

Automatic Dependency Injection registration using C# Source Generators.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages