ServiceScan.SourceGenerator 3.0.2

dotnet add package ServiceScan.SourceGenerator --version 3.0.2
                    
NuGet\Install-Package ServiceScan.SourceGenerator -Version 3.0.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="ServiceScan.SourceGenerator" Version="3.0.2">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ServiceScan.SourceGenerator" Version="3.0.2" />
                    
Directory.Packages.props
<PackageReference Include="ServiceScan.SourceGenerator">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add ServiceScan.SourceGenerator --version 3.0.2
                    
#r "nuget: ServiceScan.SourceGenerator, 3.0.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package ServiceScan.SourceGenerator@3.0.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=ServiceScan.SourceGenerator&version=3.0.2
                    
Install as a Cake Addin
#tool nuget:?package=ServiceScan.SourceGenerator&version=3.0.2
                    
Install as a Cake Tool

ServiceScan.SourceGenerator

NuGet Version Stand With Ukraine

Source generator for services registrations inspired by Scrutor. Code generation allows to have AOT-compatible code, without an additional hit on startup performance due to runtime assembly scanning.

Installation

Add the NuGet Package to your project:

dotnet add package ServiceScan.SourceGenerator

Usage

ServiceScan generates a partial method implementation based on GenerateServiceRegistrations attribute. This attribute can be added to a partial method with IServiceCollection parameter. For example, based on the following partial method:

public static partial class ServicesExtensions
{
    [GenerateServiceRegistrations(AssignableTo = typeof(IMyService), Lifetime = ServiceLifetime.Scoped)]
    public static partial IServiceCollection AddServices(this IServiceCollection services);
}

ServiceScan will generate the following implementation:

public static partial class ServicesExtensions
{
    public static partial IServiceCollection AddServices(this IServiceCollection services)
    {
        return services
            .AddScoped<IMyService, ServiceImplementation1>()
            .AddScoped<IMyService, ServiceImplementation2>();
    }
}

The only thing left is to invoke this method on your IServiceCollection instance

services.AddServices();

Examples

Register all FluentValidation validators

Unlike using FluentValidation.DependencyInjectionExtensions package, ServiceScan is AOT-compatible, and doesn't affect startup performance:

[GenerateServiceRegistrations(AssignableTo = typeof(IValidator<>), Lifetime = ServiceLifetime.Singleton)]
public static partial IServiceCollection AddValidators(this IServiceCollection services);

Add MediatR handlers

public static IServiceCollection AddMediatR(this IServiceCollection services)
{
    return services
        .AddTransient<IMediator, Mediator>()
        .AddMediatRHandlers();
}

[GenerateServiceRegistrations(AssignableTo = typeof(IRequestHandler<>), Lifetime = ServiceLifetime.Transient)]
[GenerateServiceRegistrations(AssignableTo = typeof(IRequestHandler<,>), Lifetime = ServiceLifetime.Transient)]
private static partial IServiceCollection AddMediatRHandlers(this IServiceCollection services);

It adds MediatR requests handlers, although you might need to add other types like PipelineBehaviors or NotificationHandlers.

Add all repository types from your project based on name filter as their implemented interfaces:

[GenerateServiceRegistrations(
    TypeNameFilter = "*Repository",
    AsImplementedInterfaces = true,
    Lifetime = ServiceLifetime.Scoped)]
public static partial IServiceCollection AddRepositories(this IServiceCollection services);

Add AspNetCore Minimal API endpoints

You can add custom type handler, if you need to do something non-trivial with that type. For example, you can automatically discover and map Minimal API endpoints:

public interface IEndpoint
{
    abstract static void MapEndpoint(IEndpointRouteBuilder endpoints);
}

public class HelloWorldEndpoint : IEndpoint
{
    public static void MapEndpoint(IEndpointRouteBuilder endpoints)
    {
        endpoints.MapGet("/", () => "Hello World!");
    }
}

public static partial class ServiceCollectionExtensions
{
    [ScanForTypes(AssignableTo = typeof(IEndpoint), Handler = nameof(IEndpoint.MapEndpoint))]
    public static partial IEndpointRouteBuilder MapEndpoints(this IEndpointRouteBuilder endpoints);
}

Register Options types

Another example of Handler is to register Options types. We can define custom OptionAttribute, which allows to specify configuration section key. And then read that value in our Handler:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class OptionAttribute(string? section = null) : Attribute
{
    public string? Section { get; } = section;
}

[Option]
public record RootSection { }

[Option("SectionOption")]
public record SectionOption { }

public static partial class ServiceCollectionExtensions
{
    [ScanForTypes(AttributeFilter = typeof(OptionAttribute), Handler = nameof(AddOption))]
    public static partial IServiceCollection AddOptions(this IServiceCollection services, IConfiguration configuration);

    private static void AddOption<T>(IServiceCollection services, IConfiguration configuration) where T : class
    {
        var sectionKey = typeof(T).GetCustomAttribute<OptionAttribute>()?.Section;
        var section = sectionKey is null ? configuration : configuration.GetSection(sectionKey);
        services.Configure<T>(section);
    }
}

Apply EF Core IEntityTypeConfiguration types

public static partial class ModelBuilderExtensions
{
    [ScanForTypes(AssignableTo = typeof(IEntityTypeConfiguration<>), Handler = nameof(ApplyConfiguration))]
    public static partial ModelBuilder ApplyEntityConfigurations(this ModelBuilder modelBuilder);

    private static void ApplyConfiguration<T, TEntity>(ModelBuilder modelBuilder)
        where T : IEntityTypeConfiguration<TEntity>, new()
        where TEntity : class
    {
        modelBuilder.ApplyConfiguration(new T());
    }
}

Get all matched types as a collection

When Handler is omitted and the method returns Type[] or IEnumerable<Type>, ScanForTypes returns a collection of matched types:

public static partial class TypeDiscovery
{
    [ScanForTypes(AssignableTo = typeof(IService))]
    public static partial Type[] GetAllServiceTypes();
}

Map matched types to a custom result type

When the method returns TResponse[] or IEnumerable<TResponse>, specify a Handler that maps each found type to TResponse:

public static partial class TypeDiscovery
{
    [ScanForTypes(AssignableTo = typeof(IService), Handler = nameof(Describe))]
    public static partial ServiceDescriptor[] GetServiceDescriptors();

    private static ServiceDescriptor Describe<T>() where T : IService
        => ServiceDescriptor.Transient(typeof(IService), typeof(T));
}

Parameters

GenerateServiceRegistrations attribute has the following properties: | Property | Description | | --- | --- | | FromAssemblyOf | Sets the assembly containing the given type as the source of types to register. If not specified, the assembly containing the method with this attribute will be used. | | AssemblyNameFilter | Sets this value to filter scanned assemblies by assembly name. It allows applying an attribute to multiple assemblies. For example, this allows scanning all assemblies from your solution. This option is incompatible with FromAssemblyOf. You can use '' wildcards. You can also use ',' to separate multiple filters. Be careful to include a limited number of assemblies, as it can affect build and editor performance. | | AssignableTo | Sets the type that the registered types must be assignable to. Types will be registered with this type as the service type, unless AsImplementedInterfaces or AsSelf is set. | | ExcludeAssignableTo | Sets the type that the registered types must not be assignable to. | | Lifetime | Sets the lifetime of the registered services. ServiceLifetime.Transient is used if not specified. | | AsImplementedInterfaces | If set to true, types will be registered as their implemented interfaces instead of their actual type. | | AsSelf | If set to true, types will be registered with their actual type. It can be combined with AsImplementedInterfaces. In this case, implemented interfaces will be "forwarded" to the "self" implementation. | | TypeNameFilter | Sets this value to filter the types to register by their full name. You can use '' wildcards. You can also use ',' to separate multiple filters. | | AttributeFilter | Filters types by the specified attribute type being present. | | ExcludeByTypeName | Sets this value to exclude types from being registered by their full name. You can use '*' wildcards. You can also use ',' to separate multiple filters. | | ExcludeByAttribute | Excludes matching types by the specified attribute type being present. | | KeySelector | Sets this property to add types as keyed services. This property should point to one of the following: <br>- The name of a static method in the current type with a string return type. The method should be either generic or have a single parameter of type Type. <br>- A constant field or static property in the implementation type. | | CustomHandler | (Obsolete — use ScanForTypes instead.) Sets this property to invoke a custom method for each type found instead of regular registration logic. |

ScanForTypes attribute is used to invoke a custom method for each matched type. It has the same filtering properties as GenerateServiceRegistrations, but without the registration-specific ones (Lifetime, AsImplementedInterfaces, AsSelf, KeySelector): | Property | Description | | --- | --- | | Handler | Sets this property to invoke a custom method for each type found. This property should point to one of the following: <br>- Name of a generic method in the current type. <br>- Static method name in found types. <br>Note: Types are automatically filtered by the generic constraints defined on the method's type parameters (e.g., class, struct, new(), interface constraints). | | FromAssemblyOf | Sets the assembly containing the given type as the source of types to scan. If not specified, the assembly containing the method with this attribute will be used. | | AssemblyNameFilter | Sets this value to filter scanned assemblies by assembly name. This option is incompatible with FromAssemblyOf. You can use '' wildcards. You can also use ',' to separate multiple filters. | | AssignableTo | Sets the type that the scanned types must be assignable to. | | ExcludeAssignableTo | Sets the type that the scanned types must not be assignable to. | | TypeNameFilter | Sets this value to filter the types by their full name. You can use '' wildcards. You can also use ',' to separate multiple filters. | | AttributeFilter | Filters types by the specified attribute type being present. | | ExcludeByTypeName | Sets this value to exclude types by their full name. You can use '*' wildcards. You can also use ',' to separate multiple filters. | | ExcludeByAttribute | Excludes matching types by the specified attribute type being present. |

There are no supported framework assets in this package.

Learn more about Target Frameworks and .NET Standard.

  • .NETStandard 2.0

    • No dependencies.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on ServiceScan.SourceGenerator:

Package Downloads
MVFC.Pack.IoC

Metapackage para padronizar e acelerar a configuração de inversão de controle (IoC) em aplicações .NET 9 | 10. Inclui Mediator (Source Generator), ServiceScan, FluentValidation DI e HttpClientFactory.

GitHub repositories (3)

Showing the top 3 popular GitHub repositories that depend on ServiceScan.SourceGenerator:

Repository Stars
SubnauticaNitrox/Nitrox
An open-source, multiplayer modification for the game Subnautica.
IvanJosipovic/KubeUI
Kubernetes User Interface
Papela/Nitrox-Cracked-Mod
An open-source, multiplayer modification for the game Subnautica (Cracked).
Version Downloads Last Updated
3.0.2 135 3/26/2026
2.4.1 83,782 10/22/2025
2.3.4 5,073 10/1/2025
2.3.2 7,817 8/23/2025
2.2.2 3,290 8/11/2025
2.2.1 2,156 7/25/2025
2.1.3 297 7/19/2025
2.1.2 8,318 6/17/2025
2.1.1 1,862 5/31/2025
1.5.4 713 5/19/2025
1.5.2 745 5/11/2025
1.5.1 246 5/10/2025
1.4.6 7,329 3/25/2025
1.4.5 1,430 3/21/2025
1.3.6 185,714 12/23/2024
1.3.4 410 12/22/2024
1.2.5 6,476 9/30/2024
1.1.2 2,981 6/13/2024
1.0.7 198 6/12/2024
Loading failed