Skip to main content

ServiceScan.SourceGenerator by Oleksandr Liakhevych

Nuget / site data

Nuget GitHub last commit GitHub Repo stars

Details

Info

info

Name: ServiceScan.SourceGenerator

Package Description

Author: Oleksandr Liakhevych

NuGet: https://www.nuget.org/packages/ServiceScan.SourceGenerator/

You can find more details at https://github.com/Dreamescaper/ServiceScan.SourceGenerator

Source : https://github.com/Dreamescaper/ServiceScan.SourceGenerator

Original Readme

note

ServiceScan.SourceGenerator

NuGet Version

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.

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 handlers, which would work for simple cases, 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",
AsImplemetedInterfaces = true,
Lifetime = ServiceLifetime.Scoped)]
private static partial IServiceCollection AddRepositories(this IServiceCollection services);

Parameters

GenerateServiceRegistrations attribute has the following properties: | Property | Description | | --- | --- | | FromAssemblyOf |Set 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. | | AssignableTo | Set 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. | | Lifetime | Set the lifetime of the registered services. ServiceLifetime.Transient is used if not specified. | | AsImplementedInterfaces | If true, the registered types will be registered as implemented interfaces instead of their actual type. | | AsSelf | If true, types will be registered with their actual type. It can be combined with AsImplementedInterfaces. In that case implemeted interfaces will be "forwarded" to an actual implementation type | | TypeNameFilter | Set this value to filter the types to register by their full name. You can use '*' wildcards. You can also use ',' to separate multiple filters. |

About

note

Generating service collection / DI registration

How to use

Example ( source csproj, source files )

This is the CSharp Project that references ServiceScan.SourceGenerator

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ServiceScan.SourceGenerator" Version="1.1.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
</ItemGroup>
</Project>

Generated Files

Those are taken from $(BaseIntermediateOutputPath)\GX

#nullable enable

using System;
using System.Diagnostics;
using Microsoft.Extensions.DependencyInjection;

namespace ServiceScan.SourceGenerator;

[Conditional("CODE_ANALYSIS")]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
internal class GenerateServiceRegistrationsAttribute : Attribute
{
/// <summary>
/// Set 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.
/// </summary>
public Type? FromAssemblyOf { get; set; }

/// <summary>
/// Set the type that the registered types must be assignable to.
/// Types will be registered with this type as the service type,
/// unless <see cref="AsImplementedInterfaces"/> or <see cref="AsSelf"/> is set.
/// </summary>
public Type? AssignableTo { get; set; }

/// <summary>
/// Set the lifetime of the registered services.
/// <see cref="ServiceLifetime.Transient"/> is used if not specified.
/// </summary>
public ServiceLifetime Lifetime { get; set; }

/// <summary>
/// If set to true, types will be registered as implemented interfaces instead of their actual type.
/// </summary>
public bool AsImplementedInterfaces { get; set; }

/// <summary>
/// If set to true, types will be registered with their actual type.
/// It can be combined with <see cref="AsImplementedInterfaces"/>, in that case implemeted interfaces will be
/// "forwarded" to "self" implementation.
/// </summary>
public bool AsSelf { get; set; }

/// <summary>
/// Set this value to filter the types to register by their full name.
/// You can use '*' wildcards.
/// You can also use ',' to separate multiple filters.
/// </summary>
/// <example>Namespace.With.Services.*</example>
/// <example>*Service,*Factory</example>
public string? TypeNameFilter { get; set; }
}

Usefull

Download Example (.NET C# )

Share ServiceScan.SourceGenerator

https://ignatandrei.github.io/RSCG_Examples/v2/docs/ServiceScan.SourceGenerator

In the same category (DependencyInjection) - 5 other generators

AutoRegisterInject

depso

FactoryGenerator

Injectio

jab