< Summary

Information
Class: NexusLabs.Needlr.Generators.TypeRegistryGenerator
Assembly: NexusLabs.Needlr.Generators
File(s): /home/runner/work/needlr/needlr/src/NexusLabs.Needlr.Generators/TypeRegistryGenerator.cs
Line coverage
99%
Covered lines: 702
Uncovered lines: 1
Coverable lines: 703
Total lines: 1084
Line coverage: 99.8%
Branch coverage
91%
Covered branches: 280
Total branches: 306
Branch coverage: 91.5%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
Initialize(...)98.43%6464100%
GetBreadcrumbLevel(...)100%88100%
GetProjectDirectory(...)100%44100%
GetDiagnosticOptions(...)100%11100%
ShouldExportGraph(...)100%44100%
ShouldEmitRegistrationManifest(...)100%22100%
IsAotProject(...)100%88100%
GetAttributeInfoFromCompilation(...)95.83%2424100%
DiscoverTypes(...)100%3030100%
CollectTypesFromAssembly(...)83.33%138138100%
GenerateTypeRegistrySource(...)100%1414100%
GenerateRegisterOptionsMethod(...)90%101094.73%

File(s)

/home/runner/work/needlr/needlr/src/NexusLabs.Needlr.Generators/TypeRegistryGenerator.cs

#LineLine coverage
 1using Microsoft.CodeAnalysis;
 2using Microsoft.CodeAnalysis.Text;
 3using NexusLabs.Needlr.Generators.Helpers;
 4using NexusLabs.Needlr.Generators.Models;
 5using System.Text;
 6
 7namespace NexusLabs.Needlr.Generators;
 8
 9/// <summary>
 10/// Incremental source generator that produces a compile-time type registry
 11/// for dependency injection, eliminating runtime reflection.
 12/// </summary>
 13[Generator(LanguageNames.CSharp)]
 14public sealed class TypeRegistryGenerator : IIncrementalGenerator
 15{
 16    private const string GenerateTypeRegistryAttributeName = "NexusLabs.Needlr.Generators.GenerateTypeRegistryAttribute"
 17
 18    public void Initialize(IncrementalGeneratorInitializationContext context)
 19    {
 20        // Combine compilation with analyzer config options to read MSBuild properties
 60921        var compilationAndOptions = context.CompilationProvider
 60922            .Combine(context.AnalyzerConfigOptionsProvider);
 23
 24        // ForAttributeWithMetadataName doesn't work for assembly-level attributes.
 25        // Instead, we register directly on the compilation provider and check
 26        // compilation.Assembly.GetAttributes() for [GenerateTypeRegistry].
 60927        context.RegisterSourceOutput(compilationAndOptions, static (spc, source) =>
 60928        {
 60929            var (compilation, configOptions) = source;
 60930
 60931            var attributeInfo = GetAttributeInfoFromCompilation(compilation);
 60932            if (attributeInfo == null)
 133                return;
 60934
 60835            var info = attributeInfo.Value;
 60836            var assemblyName = compilation.AssemblyName ?? "Generated";
 60937
 60938            // Read breadcrumb level from MSBuild property
 60839            var breadcrumbLevel = GetBreadcrumbLevel(configOptions);
 60840            var projectDirectory = GetProjectDirectory(configOptions);
 60841            var breadcrumbs = new BreadcrumbWriter(breadcrumbLevel);
 60942
 60943            // Check if this is an AOT project
 60844            var isAotProject = IsAotProject(configOptions);
 60945
 60846            var discoveryResult = DiscoverTypes(
 60847                compilation,
 60848                info.NamespacePrefixes,
 60849                info.ExcludeNamespacePrefixes,
 60850                info.IncludeSelf);
 60951
 60852            var boundCompilation = FactoryConsumerDiscoveryHelper.BindFactoryConsumers(
 60853                compilation,
 60854                discoveryResult.Factories,
 60855                assemblyName,
 60856                breadcrumbs,
 60857                projectDirectory);
 60858            if (!ReferenceEquals(boundCompilation, compilation))
 60959            {
 4360                discoveryResult = DiscoverTypes(
 4361                    boundCompilation,
 4362                    info.NamespacePrefixes,
 4363                    info.ExcludeNamespacePrefixes,
 4364                    info.IncludeSelf);
 60965            }
 60966
 60967            // Discover referenced assemblies with [GenerateTypeRegistry] for forced loading.
 60968            // Done early so the empty-result check below can include this in its decision.
 60969            // Note: Order of force-loading doesn't matter; ordering is applied at service registration time
 60870            var referencedAssemblies = AssemblyDiscoveryHelper.DiscoverReferencedAssembliesWithTypeRegistry(compilation)
 271                .OrderBy(a => a, StringComparer.OrdinalIgnoreCase)
 60872                .ToList();
 60973
 60974            // Nothing was discovered: no injectable types, factories, providers, options,
 60975            // interceptors, hosted services, plugins, no referenced assemblies to force-load,
 60976            // no inaccessible type errors, and no missing TypeRegistry warnings.
 60877            var nothingDiscovered =
 60878                discoveryResult.InjectableTypes.Count == 0 &&
 60879                discoveryResult.PluginTypes.Count == 0 &&
 60880                discoveryResult.Decorators.Count == 0 &&
 60881                discoveryResult.InterceptedServices.Count == 0 &&
 60882                discoveryResult.Factories.Count == 0 &&
 60883                discoveryResult.Options.Count == 0 &&
 60884                discoveryResult.HttpClients.Count == 0 &&
 60885                discoveryResult.HostedServices.Count == 0 &&
 60886                discoveryResult.Providers.Count == 0 &&
 60887                discoveryResult.ComposedRegistrations.Count == 0 &&
 60888                discoveryResult.InaccessibleTypes.Count == 0 &&
 60889                discoveryResult.MissingTypeRegistryPlugins.Count == 0 &&
 60890                referencedAssemblies.Count == 0;
 60991
 60892            var registrationPlan = GeneratedRegistrationPlanBuilder.Create(
 60893                assemblyName,
 60894                isAotProject,
 60895                registersServiceCatalog: !nothingDiscovered,
 60896                referencedAssemblies,
 60897                discoveryResult);
 60898            if (ShouldEmitRegistrationManifest(configOptions))
 60999            {
 18100                var registrationManifestSource =
 18101                    CodeGen.RegistrationManifestCodeGenerator.GenerateSource(
 18102                        registrationPlan,
 18103                        breadcrumbs);
 18104                spc.AddSource(
 18105                    "NeedlrRegistrationManifest.g.cs",
 18106                    GeneratedSourceText.Create(registrationManifestSource));
 609107            }
 609108
 609109            // A type-less assembly that still carries [GenerateTypeRegistry] (guaranteed here by the
 609110            // attributeInfo guard above) is a declared Needlr participant. Consumers force-load
 609111            // typeof({Assembly}.Generated.TypeRegistry) for every attribute-carrying referenced
 609112            // assembly, so emitting nothing makes those consumers fail to compile with CS0234. Emit
 609113            // a minimal registry instead. It depends only on the attributes package (never the
 609114            // injection packages), so it compiles whether or not this assembly references them — a
 609115            // domain, contracts, or documentation-only project participates without being forced to
 609116            // take a dependency it would not otherwise have.
 608117            if (nothingDiscovered)
 609118            {
 11119                var emptyRegistrySource =
 11120                    CodeGen.EmptyTypeRegistryCodeGenerator.GenerateTypeRegistrySource(
 11121                        registrationPlan,
 11122                        breadcrumbs);
 11123                spc.AddSource("TypeRegistry.g.cs", GeneratedSourceText.Create(emptyRegistrySource));
 609124
 11125                var emptyBootstrapSource =
 11126                    CodeGen.EmptyTypeRegistryCodeGenerator.GenerateBootstrapSource(
 11127                        registrationPlan,
 11128                        breadcrumbs);
 11129                spc.AddSource("NeedlrSourceGenBootstrap.g.cs", GeneratedSourceText.Create(emptyBootstrapSource));
 11130                return;
 609131            }
 609132
 609133            // Report errors for inaccessible internal types in referenced assemblies
 6468134            foreach (var inaccessibleType in discoveryResult.InaccessibleTypes)
 609135            {
 2637136                spc.ReportDiagnostic(Diagnostic.Create(
 2637137                    DiagnosticDescriptors.InaccessibleInternalType,
 2637138                    Location.None,
 2637139                    inaccessibleType.TypeName,
 2637140                    inaccessibleType.AssemblyName));
 609141            }
 609142
 609143            // Report errors for referenced assemblies with internal plugin types but no [GenerateTypeRegistry]
 1196144            foreach (var missingPlugin in discoveryResult.MissingTypeRegistryPlugins)
 609145            {
 1146                spc.ReportDiagnostic(Diagnostic.Create(
 1147                    DiagnosticDescriptors.MissingGenerateTypeRegistryAttribute,
 1148                    Location.None,
 1149                    missingPlugin.AssemblyName,
 1150                    missingPlugin.TypeName));
 609151            }
 609152
 609153            // NDLRGEN020: Previously reported error if [Options] used in AOT project
 609154            // Now removed for parity - we generate best-effort code and let unsupported
 609155            // types fail at runtime (matching non-AOT ConfigurationBinder behavior)
 609156
 609157            // NDLRGEN021: Report warning for non-partial positional records
 1374158            foreach (var opt in discoveryResult.Options.Where(o => o.IsNonPartialPositionalRecord))
 609159            {
 2160                spc.ReportDiagnostic(Diagnostic.Create(
 2161                    DiagnosticDescriptors.PositionalRecordMustBePartial,
 2162                    Location.None,
 2163                    opt.TypeName));
 609164            }
 609165
 609166            // NDLRGEN022: Detect disposable captive dependencies using inferred lifetimes
 597167            CaptiveDependencyAnalyzer.ReportDisposableCaptiveDependencies(spc, discoveryResult);
 609168
 609169            // NDLRGEN038: Report skipped composition registrations whose discovered type argument(s)
 609170            // violate the composition's generic constraints.
 1262171            foreach (var violation in discoveryResult.ComposedConstraintViolations)
 609172            {
 34173                spc.ReportDiagnostic(Diagnostic.Create(
 34174                    DiagnosticDescriptors.ComposedTypeArgumentViolatesConstraints,
 34175                    Location.None,
 34176                    violation.CompositionTypeName,
 34177                    violation.TypeArgumentName,
 34178                    violation.SourceInterfaceName));
 609179            }
 609180
 597181            var sourceText = GenerateTypeRegistrySource(
 597182                registrationPlan,
 597183                breadcrumbs,
 597184                projectDirectory);
 597185            spc.AddSource("TypeRegistry.g.cs", GeneratedSourceText.Create(sourceText));
 609186
 597187            var bootstrapText = CodeGen.BootstrapCodeGenerator.GenerateModuleInitializerBootstrapSource(
 597188                registrationPlan.AssemblyName,
 597189                registrationPlan.ReferencedRegistryAssemblies,
 597190                breadcrumbs,
 597191                registrationPlan.HasFactoryRegistrations,
 597192                registrationPlan.HasConfigBoundRegistrations,
 597193                registrationPlan.HasProviderRegistrations);
 597194            spc.AddSource("NeedlrSourceGenBootstrap.g.cs", GeneratedSourceText.Create(bootstrapText));
 609195
 609196            // Generate interceptor proxy classes if any were discovered
 597197            if (registrationPlan.DiscoveryResult.InterceptedServices.Count > 0)
 609198            {
 15199                var interceptorProxiesText = CodeGen.InterceptorCodeGenerator.GenerateInterceptorProxiesSource(
 15200                    registrationPlan.DiscoveryResult.InterceptedServices,
 15201                    registrationPlan.AssemblyName,
 15202                    breadcrumbs,
 15203                    projectDirectory);
 15204                spc.AddSource("InterceptorProxies.g.cs", GeneratedSourceText.Create(interceptorProxiesText));
 609205            }
 609206
 609207            // Generate factory classes if any were discovered
 597208            if (registrationPlan.HasFactoryRegistrations)
 609209            {
 45210                var factoriesText = CodeGen.FactoryCodeGenerator.GenerateFactoriesSource(
 45211                    registrationPlan.EmittedFactories,
 45212                    registrationPlan.AssemblyName,
 45213                    breadcrumbs,
 45214                    projectDirectory);
 45215                spc.AddSource("Factories.g.cs", GeneratedSourceText.Create(factoriesText));
 609216            }
 609217
 609218            // Generate provider classes if any were discovered
 597219            if (registrationPlan.HasProviderRegistrations)
 609220            {
 609221                // Interface-based providers go in the Generated namespace
 18222                var interfaceProviders = registrationPlan.EmittedProviders
 19223                    .Where(p => p.IsInterface)
 18224                    .ToList();
 18225                if (interfaceProviders.Count > 0)
 609226                {
 12227                    var providersText = CodeGen.ProviderCodeGenerator.GenerateProvidersSource(
 12228                        interfaceProviders,
 12229                        registrationPlan.AssemblyName,
 12230                        breadcrumbs,
 12231                        projectDirectory);
 12232                    spc.AddSource("Providers.g.cs", GeneratedSourceText.Create(providersText));
 609233                }
 609234
 609235                // Shorthand class providers need to be generated in their original namespace
 18236                var classProviders = registrationPlan.EmittedProviders
 19237                    .Where(p => !p.IsInterface && p.IsPartial)
 18238                    .ToList();
 48239                foreach (var provider in classProviders)
 609240                {
 6241                    var providerText = CodeGen.ProviderCodeGenerator.GenerateShorthandProviderSource(
 6242                        provider,
 6243                        registrationPlan.AssemblyName,
 6244                        breadcrumbs,
 6245                        projectDirectory);
 6246                    spc.AddSource($"Provider.{provider.SimpleTypeName}.g.cs", GeneratedSourceText.Create(providerText));
 609247                }
 609248            }
 609249
 609250            // Generate options validator classes if any have validation methods
 597251            var optionsWithValidators = registrationPlan.DiscoveryResult.Options
 176252                .Where(o => o.HasValidatorMethod)
 597253                .ToList();
 597254            if (optionsWithValidators.Count > 0)
 609255            {
 22256                var validatorsText = CodeGen.OptionsCodeGenerator.GenerateOptionsValidatorsSource(
 22257                    optionsWithValidators,
 22258                    registrationPlan.AssemblyName,
 22259                    breadcrumbs,
 22260                    projectDirectory);
 22261                spc.AddSource("OptionsValidators.g.cs", GeneratedSourceText.Create(validatorsText));
 609262            }
 609263
 609264            // Generate DataAnnotations validator classes if any have DataAnnotation attributes
 597265            var optionsWithDataAnnotations = registrationPlan.DiscoveryResult.Options
 176266                .Where(o => o.HasDataAnnotations)
 597267                .ToList();
 597268            if (optionsWithDataAnnotations.Count > 0)
 609269            {
 19270                var dataAnnotationsValidatorsText = CodeGen.OptionsCodeGenerator.GenerateDataAnnotationsValidatorsSource
 19271                    optionsWithDataAnnotations,
 19272                    registrationPlan.AssemblyName,
 19273                    breadcrumbs,
 19274                    projectDirectory);
 19275                spc.AddSource("OptionsDataAnnotationsValidators.g.cs", GeneratedSourceText.Create(dataAnnotationsValidat
 609276            }
 609277
 609278            // Generate parameterless constructors for partial positional records with [Options]
 597279            var optionsNeedingConstructors = registrationPlan.DiscoveryResult.Options
 176280                .Where(o => o.NeedsGeneratedConstructor)
 597281                .ToList();
 597282            if (optionsNeedingConstructors.Count > 0)
 609283            {
 12284                var constructorsText = CodeGen.OptionsCodeGenerator.GeneratePositionalRecordConstructorsSource(
 12285                    optionsNeedingConstructors,
 12286                    registrationPlan.AssemblyName,
 12287                    breadcrumbs,
 12288                    projectDirectory);
 12289                spc.AddSource("OptionsConstructors.g.cs", GeneratedSourceText.Create(constructorsText));
 609290            }
 609291
 609292            // Generate ServiceCatalog for runtime introspection
 597293            var catalogText = CodeGen.ServiceCatalogCodeGenerator.GenerateServiceCatalogSource(
 597294                registrationPlan,
 597295                projectDirectory,
 597296                breadcrumbs);
 597297            spc.AddSource("ServiceCatalog.g.cs", GeneratedSourceText.Create(catalogText));
 609298
 609299            // Generate diagnostic output files if configured
 597300            var diagnosticOptions = GetDiagnosticOptions(configOptions);
 597301            if (diagnosticOptions.Enabled)
 609302            {
 109303                var referencedAssemblyTypes = AssemblyDiscoveryHelper.DiscoverReferencedAssemblyTypesForDiagnostics(comp
 109304                var diagnosticsText = DiagnosticsGenerator.GenerateDiagnosticsSource(discoveryResult, assemblyName, proj
 109305                spc.AddSource("NeedlrDiagnostics.g.cs", GeneratedSourceText.Create(diagnosticsText));
 609306            }
 609307
 609308            // Generate IDE graph export if configured
 597309            if (ShouldExportGraph(configOptions))
 609310            {
 609311                // Discover types from referenced assemblies with [GenerateTypeRegistry] for graph inclusion
 19312                var referencedAssemblyTypesForGraph = AssemblyDiscoveryHelper.DiscoverReferencedAssemblyTypesForGraph(co
 609313
 19314                var graphJson = Export.GraphExporter.GenerateGraphJson(
 19315                    discoveryResult,
 19316                    assemblyName,
 19317                    projectDirectory,
 19318                    diagnostics: null,
 19319                    referencedAssemblyTypes: referencedAssemblyTypesForGraph);
 609320
 609321                // Embed graph as a comment in a generated file so it's accessible
 609322                // The actual JSON is written to obj folder via the generated code
 19323                var graphSourceText = Export.GraphExporter.GenerateGraphExportSource(graphJson, assemblyName, breadcrumb
 19324                spc.AddSource("NeedlrGraph.g.cs", GeneratedSourceText.Create(graphSourceText));
 609325            }
 1206326        });
 609327    }
 328
 329    internal static BreadcrumbLevel GetBreadcrumbLevel(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider 
 330    {
 723331        if (configOptions.GlobalOptions.TryGetValue("build_property.NeedlrBreadcrumbLevel", out var levelStr) &&
 723332            !string.IsNullOrWhiteSpace(levelStr))
 333        {
 259334            if (levelStr.Equals("None", StringComparison.OrdinalIgnoreCase))
 17335                return BreadcrumbLevel.None;
 242336            if (levelStr.Equals("Verbose", StringComparison.OrdinalIgnoreCase))
 28337                return BreadcrumbLevel.Verbose;
 338        }
 339
 340        // Default to Minimal
 678341        return BreadcrumbLevel.Minimal;
 342    }
 343
 344    private static string? GetProjectDirectory(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider configOp
 345    {
 346        // Try to get the project directory from MSBuild properties
 608347        if (configOptions.GlobalOptions.TryGetValue("build_property.ProjectDir", out var projectDir) &&
 608348            !string.IsNullOrWhiteSpace(projectDir))
 349        {
 4350            return projectDir.TrimEnd('/', '\\');
 351        }
 352
 604353        return null;
 354    }
 355
 356    private static DiagnosticOptions GetDiagnosticOptions(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvid
 357    {
 597358        configOptions.GlobalOptions.TryGetValue("build_property.NeedlrDiagnostics", out var enabled);
 597359        configOptions.GlobalOptions.TryGetValue("build_property.NeedlrDiagnosticsPath", out var outputPath);
 597360        configOptions.GlobalOptions.TryGetValue("build_property.NeedlrDiagnosticsFilter", out var filter);
 361
 597362        return DiagnosticOptions.Parse(enabled, outputPath, filter);
 363    }
 364
 365    /// <summary>
 366    /// Checks if the IDE graph export is enabled.
 367    /// </summary>
 368    private static bool ShouldExportGraph(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider configOptions
 369    {
 370        // Export graph is disabled by default
 371        // Enable with NeedlrExportGraph=true in project file
 597372        if (configOptions.GlobalOptions.TryGetValue("build_property.NeedlrExportGraph", out var exportGraph) &&
 597373            exportGraph.Equals("true", StringComparison.OrdinalIgnoreCase))
 374        {
 19375            return true;
 376        }
 578377        return false;
 378    }
 379
 380    private static bool ShouldEmitRegistrationManifest(
 381        Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider configOptions)
 382    {
 608383        return configOptions.GlobalOptions.TryGetValue(
 608384                "build_property.NeedlrEmitRegistrationManifest",
 608385                out var enabled) &&
 608386            enabled.Equals(
 608387                "true",
 608388                StringComparison.OrdinalIgnoreCase);
 389    }
 390
 391    /// <summary>
 392    /// Checks if the project is configured for AOT compilation.
 393    /// Returns true if either PublishAot or IsAotCompatible is set to true.
 394    /// </summary>
 395    private static bool IsAotProject(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider configOptions)
 396    {
 608397        if (configOptions.GlobalOptions.TryGetValue("build_property.PublishAot", out var publishAot) &&
 608398            publishAot.Equals("true", StringComparison.OrdinalIgnoreCase))
 399        {
 86400            return true;
 401        }
 402
 522403        if (configOptions.GlobalOptions.TryGetValue("build_property.IsAotCompatible", out var isAotCompatible) &&
 522404            isAotCompatible.Equals("true", StringComparison.OrdinalIgnoreCase))
 405        {
 1406            return true;
 407        }
 408
 521409        return false;
 410    }
 411
 412    private static AttributeInfo? GetAttributeInfoFromCompilation(Compilation compilation)
 413    {
 414        // Get assembly-level attributes directly from the compilation
 1826415        foreach (var attribute in compilation.Assembly.GetAttributes())
 416        {
 608417            var attrClassName = attribute.AttributeClass?.ToDisplayString();
 418
 419            // Check if this is our attribute (various name format possibilities)
 608420            if (attrClassName != GenerateTypeRegistryAttributeName)
 421                continue;
 422
 608423            string[]? namespacePrefixes = null;
 608424            string[]? excludeNamespacePrefixes = null;
 608425            var includeSelf = true;
 426
 1578427            foreach (var namedArg in attribute.NamedArguments)
 428            {
 181429                switch (namedArg.Key)
 430                {
 431                    case "IncludeNamespacePrefixes":
 169432                        if (!namedArg.Value.IsNull && namedArg.Value.Values.Length > 0)
 433                        {
 169434                            namespacePrefixes = namedArg.Value.Values
 171435                                .Where(v => v.Value is string)
 171436                                .Select(v => (string)v.Value!)
 169437                                .ToArray();
 438                        }
 169439                        break;
 440
 441                    case "ExcludeNamespacePrefixes":
 1442                        if (!namedArg.Value.IsNull && namedArg.Value.Values.Length > 0)
 443                        {
 1444                            excludeNamespacePrefixes = namedArg.Value.Values
 1445                                .Where(v => v.Value is string)
 1446                                .Select(v => (string)v.Value!)
 1447                                .ToArray();
 448                        }
 1449                        break;
 450
 451                    case "IncludeSelf":
 11452                        if (namedArg.Value.Value is bool selfValue)
 453                        {
 11454                            includeSelf = selfValue;
 455                        }
 456                        break;
 457                }
 458            }
 459
 608460            return new AttributeInfo(namespacePrefixes, excludeNamespacePrefixes, includeSelf);
 461        }
 462
 1463        return null;
 464    }
 465
 466    private static DiscoveryResult DiscoverTypes(
 467        Compilation compilation,
 468        string[]? namespacePrefixes,
 469        string[]? excludeNamespacePrefixes,
 470        bool includeSelf)
 471    {
 651472        var injectableTypes = new List<DiscoveredType>();
 651473        var pluginTypes = new List<DiscoveredPlugin>();
 651474        var decorators = new List<DiscoveredDecorator>();
 651475        var openDecorators = new List<DiscoveredOpenDecorator>();
 651476        var composedMarkers = new List<DiscoveredComposedMarker>();
 651477        var composedCandidateTypes = new List<INamedTypeSymbol>();
 651478        var interceptedServices = new List<DiscoveredInterceptedService>();
 651479        var factories = new List<DiscoveredFactory>();
 651480        var options = new List<DiscoveredOptions>();
 651481        var hostedServices = new List<DiscoveredHostedService>();
 651482        var providers = new List<DiscoveredProvider>();
 651483        var httpClients = new List<DiscoveredHttpClient>();
 651484        var inaccessibleTypes = new List<InaccessibleType>();
 651485        var prefixList = namespacePrefixes?.ToList();
 651486        var excludePrefixList = excludeNamespacePrefixes?.ToList();
 487
 488        // Compute the generated namespace for the current assembly
 651489        var currentAssemblyName = compilation.Assembly.Name;
 651490        var safeAssemblyName = GeneratorHelpers.SanitizeIdentifier(currentAssemblyName);
 651491        var generatedNamespace = $"{safeAssemblyName}.Generated";
 492
 493        // Collect types from the current compilation if includeSelf is true
 651494        if (includeSelf)
 495        {
 649496            CollectTypesFromAssembly(compilation.Assembly, prefixList, excludePrefixList, injectableTypes, pluginTypes, 
 497        }
 498
 499        // Collect types from all referenced assemblies
 221264500        foreach (var reference in compilation.References)
 501        {
 109981502            if (compilation.GetAssemblyOrModuleSymbol(reference) is IAssemblySymbol assemblySymbol)
 503            {
 504                // Skip assemblies that already have [GenerateTypeRegistry] — those assemblies
 505                // register their own types at runtime via their own TypeRegistry and cascade
 506                // loading. Scanning them here would trigger false NDLRGEN001 errors for their
 507                // internal types.
 109673508                if (TypeDiscoveryHelper.HasGenerateTypeRegistryAttribute(assemblySymbol))
 509                    continue;
 510
 511                // For referenced assemblies, they use their own generated namespace
 109654512                var refSafeAssemblyName = GeneratorHelpers.SanitizeIdentifier(assemblySymbol.Name);
 109654513                var refGeneratedNamespace = $"{refSafeAssemblyName}.Generated";
 109654514                CollectTypesFromAssembly(assemblySymbol, prefixList, excludePrefixList, injectableTypes, pluginTypes, de
 515            }
 516        }
 517
 518        // Expand open generic decorators into closed decorator registrations
 651519        if (openDecorators.Count > 0)
 520        {
 6521            CodeGen.DecoratorsCodeGenerator.ExpandOpenDecorators(injectableTypes, openDecorators, decorators);
 522        }
 523
 524        // Expand [RegisterClosedOverImplementationsOf] markers into closed composition registrations.
 651525        var composedRegistrations = new List<DiscoveredComposedRegistration>();
 651526        var composedConstraintViolations = new List<ComposedConstraintViolation>();
 651527        if (composedMarkers.Count > 0)
 528        {
 68529            ComposedRegistrationDiscoveryHelper.Expand(
 68530                composedMarkers,
 68531                composedCandidateTypes,
 68532                composedRegistrations,
 68533                composedConstraintViolations);
 534        }
 535
 536        // Filter out nested options types (types used as properties in other options types)
 651537        if (options.Count > 1)
 538        {
 19539            options = OptionsDiscoveryHelper.FilterNestedOptions(options, compilation);
 540        }
 541
 542        // Check for referenced assemblies with internal plugin types but no [GenerateTypeRegistry]
 651543        var missingTypeRegistryPlugins = new List<MissingTypeRegistryPlugin>();
 221264544        foreach (var reference in compilation.References)
 545        {
 109981546            if (compilation.GetAssemblyOrModuleSymbol(reference) is IAssemblySymbol assemblySymbol)
 547            {
 548                // Skip assemblies that already have [GenerateTypeRegistry]
 109673549                if (TypeDiscoveryHelper.HasGenerateTypeRegistryAttribute(assemblySymbol))
 550                    continue;
 551
 552                // Look for internal types that implement Needlr plugin interfaces
 5380482553                foreach (var typeSymbol in TypeDiscoveryHelper.GetAllTypes(assemblySymbol.GlobalNamespace))
 554                {
 2580587555                    if (!TypeDiscoveryHelper.IsInternalOrLessAccessible(typeSymbol))
 556                        continue;
 557
 122663558                    if (!TypeDiscoveryHelper.ImplementsNeedlrPluginInterface(typeSymbol))
 559                        continue;
 560
 561                    // This is an internal plugin type in an assembly without [GenerateTypeRegistry]
 1562                    var typeName = TypeDiscoveryHelper.GetFullyQualifiedName(typeSymbol);
 1563                    missingTypeRegistryPlugins.Add(new MissingTypeRegistryPlugin(typeName, assemblySymbol.Name));
 564                }
 565            }
 566        }
 567
 651568        return new DiscoveryResult(injectableTypes, pluginTypes, decorators, inaccessibleTypes, missingTypeRegistryPlugi
 569    }
 570
 571    private static void CollectTypesFromAssembly(
 572        IAssemblySymbol assembly,
 573        IReadOnlyList<string>? namespacePrefixes,
 574        IReadOnlyList<string>? excludeNamespacePrefixes,
 575        List<DiscoveredType> injectableTypes,
 576        List<DiscoveredPlugin> pluginTypes,
 577        List<DiscoveredDecorator> decorators,
 578        List<DiscoveredOpenDecorator> openDecorators,
 579        List<DiscoveredInterceptedService> interceptedServices,
 580        List<DiscoveredFactory> factories,
 581        List<DiscoveredOptions> options,
 582        List<DiscoveredHostedService> hostedServices,
 583        List<DiscoveredProvider> providers,
 584        List<DiscoveredHttpClient> httpClients,
 585        List<InaccessibleType> inaccessibleTypes,
 586        List<DiscoveredComposedMarker> composedMarkers,
 587        List<INamedTypeSymbol> composedCandidateTypes,
 588        Compilation compilation,
 589        bool isCurrentAssembly,
 590        string generatedNamespace)
 591    {
 5386686592        foreach (var typeSymbol in TypeDiscoveryHelper.GetAllTypes(assembly.GlobalNamespace))
 593        {
 2583040594            if (!TypeDiscoveryHelper.MatchesNamespacePrefix(typeSymbol, namespacePrefixes))
 595                continue;
 596
 1887888597            if (TypeDiscoveryHelper.MatchesExclusionFilter(typeSymbol, excludeNamespacePrefixes))
 598                continue;
 599
 600            // .NET MAUI per-platform application entry points are framework-owned and carry
 601            // platform-generated interop members that are inaccessible from generated code.
 602            // Scanning them breaks the head build, so skip them before any discovery path runs.
 1887887603            if (TypeDiscoveryHelper.IsMauiPlatformEntryType(typeSymbol))
 604                continue;
 605
 606            // For referenced assemblies, check if the type would be registerable but is inaccessible
 1887883607            if (!isCurrentAssembly && TypeDiscoveryHelper.IsInternalOrLessAccessible(typeSymbol))
 608            {
 609                // Check if this type would have been registered if it were accessible
 90261610                if (TypeDiscoveryHelper.WouldBeInjectableIgnoringAccessibility(typeSymbol) ||
 90261611                    TypeDiscoveryHelper.WouldBePluginIgnoringAccessibility(typeSymbol, compilation.Assembly))
 612                {
 2853613                    var typeName = TypeDiscoveryHelper.GetFullyQualifiedName(typeSymbol);
 2853614                    inaccessibleTypes.Add(new InaccessibleType(typeName, assembly.Name));
 615                }
 2853616                continue; // Skip further processing for inaccessible types
 617            }
 618
 619            // Check for [Options] attribute
 1797622620            if (OptionsAttributeHelper.HasOptionsAttribute(typeSymbol))
 621            {
 178622                var typeName = TypeDiscoveryHelper.GetFullyQualifiedName(typeSymbol);
 178623                var optionsAttrs = OptionsAttributeHelper.GetOptionsAttributes(typeSymbol);
 178624                var sourceFilePath = typeSymbol.Locations.FirstOrDefault()?.SourceTree?.FilePath;
 625
 626                // Extract bindable properties for AOT code generation
 178627                var properties = OptionsDiscoveryHelper.ExtractBindableProperties(typeSymbol);
 628
 629                // Detect positional record (record with primary constructor parameters)
 178630                var positionalRecordInfo = OptionsDiscoveryHelper.DetectPositionalRecord(typeSymbol, properties);
 631
 724632                foreach (var optionsAttr in optionsAttrs)
 633                {
 634                    // Determine validator type and method
 184635                    var validatorTypeSymbol = optionsAttr.ValidatorType;
 184636                    var targetType = validatorTypeSymbol ?? typeSymbol; // Look for method on options class or external 
 184637                    var methodName = optionsAttr.ValidateMethod ?? "Validate"; // Convention: "Validate"
 638
 639                    // Find validation method using convention-based discovery
 184640                    var validatorMethodInfo = OptionsAttributeHelper.FindValidationMethod(
 184641                        targetType,
 184642                        typeSymbol,
 184643                        methodName,
 184644                        validatorTypeSymbol is not null,
 184645                        optionsAttr.ValidateMethod is null);
 184646                    OptionsValidatorInfo? validatorInfo = validatorMethodInfo.HasValue
 184647                        ? new OptionsValidatorInfo(
 184648                            validatorMethodInfo.Value.MethodName,
 184649                            validatorMethodInfo.Value.IsStatic,
 184650                            validatorMethodInfo.Value.UsesOptionsValidatorInterface)
 184651                        : null;
 652
 653                    // Infer section name if not provided
 184654                    var sectionName = optionsAttr.SectionName
 184655                        ?? Helpers.OptionsNamingHelper.InferSectionName(typeSymbol.Name);
 656
 184657                    var validatorTypeName = validatorTypeSymbol != null
 184658                        ? TypeDiscoveryHelper.GetFullyQualifiedName(validatorTypeSymbol)
 184659                        : null;
 660
 184661                    options.Add(new DiscoveredOptions(
 184662                        typeName,
 184663                        sectionName,
 184664                        optionsAttr.Name,
 184665                        optionsAttr.ValidateOnStart,
 184666                        assembly.Name,
 184667                        sourceFilePath,
 184668                        validatorInfo,
 184669                        optionsAttr.ValidateMethod,
 184670                        validatorTypeName,
 184671                        positionalRecordInfo,
 184672                        properties));
 673                }
 674            }
 675
 1797622676            var httpAttrInfo =
 1797622677                HttpClientOptionsAttributeHelper.GetHttpClientOptionsAttribute(
 1797622678                    typeSymbol);
 1797622679            if (httpAttrInfo.HasValue)
 680            {
 12681                var clientNamePropResult =
 12682                    HttpClientOptionsAttributeHelper.TryGetClientNameProperty(
 12683                        typeSymbol,
 12684                        out var literalValue);
 12685                var propertyNameFromType =
 12686                    clientNamePropResult == ClientNamePropertyResult.Literal
 12687                        ? literalValue
 12688                        : null;
 689
 12690                if (HttpClientOptionsAttributeHelper.TryResolveClientName(
 12691                    typeSymbol,
 12692                    httpAttrInfo.Value,
 12693                    propertyNameFromType,
 12694                    out var resolvedClientName))
 695                {
 11696                    var httpSectionName =
 11697                        HttpClientOptionsAttributeHelper.ResolveSectionName(
 11698                            httpAttrInfo.Value,
 11699                            resolvedClientName);
 11700                    var httpTypeName =
 11701                        TypeDiscoveryHelper.GetFullyQualifiedName(typeSymbol);
 11702                    var httpSourceFilePath =
 11703                        typeSymbol.Locations.FirstOrDefault()?
 11704                            .SourceTree?.FilePath;
 11705                    var capabilities =
 11706                        HttpClientOptionsAttributeHelper.DetectCapabilities(
 11707                            typeSymbol);
 708
 11709                    httpClients.Add(new DiscoveredHttpClient(
 11710                        httpTypeName,
 11711                        resolvedClientName,
 11712                        httpSectionName,
 11713                        assembly.Name,
 11714                        capabilities,
 11715                        httpSourceFilePath));
 716                }
 717            }
 718
 719            // Check for [GenerateFactory] attribute - these types get factories instead of direct registration
 1797622720            if (FactoryDiscoveryHelper.HasGenerateFactoryAttribute(typeSymbol))
 721            {
 91722                var factoryConstructors = FactoryDiscoveryHelper.GetFactoryConstructors(typeSymbol);
 91723                if (factoryConstructors.Count > 0)
 724                {
 725                    // Has at least one constructor with runtime params - generate factory
 88726                    var typeName = TypeDiscoveryHelper.GetFullyQualifiedName(typeSymbol);
 88727                    var interfaces = TypeDiscoveryHelper.GetRegisterableInterfaces(typeSymbol, compilation.Assembly);
 106728                    var interfaceNames = interfaces.Select(i => TypeDiscoveryHelper.GetFullyQualifiedName(i)).ToArray();
 88729                    var generationMode = FactoryDiscoveryHelper.GetFactoryGenerationMode(typeSymbol);
 88730                    var returnTypeOverride = FactoryDiscoveryHelper.GetFactoryReturnInterfaceType(typeSymbol);
 88731                    var sourceFilePath = typeSymbol.Locations.FirstOrDefault()?.SourceTree?.FilePath;
 732
 88733                    factories.Add(new DiscoveredFactory(
 88734                        typeName,
 88735                        interfaceNames,
 88736                        assembly.Name,
 88737                        generationMode,
 88738                        factoryConstructors.ToArray(),
 88739                        returnTypeOverride,
 88740                        sourceFilePath));
 741
 88742                    continue; // Don't add to injectable types - factory handles registration
 743                }
 744                // If no runtime params, fall through to normal direct-type registration.
 745            }
 746
 747            // Check for DecoratorFor<T> attributes
 1797534748            var decoratorInfos = TypeDiscoveryHelper.GetDecoratorForAttributes(typeSymbol);
 3595148749            foreach (var decoratorInfo in decoratorInfos)
 750            {
 40751                var sourceFilePath = typeSymbol.Locations.FirstOrDefault()?.SourceTree?.FilePath;
 40752                decorators.Add(new DiscoveredDecorator(
 40753                    decoratorInfo.DecoratorTypeName,
 40754                    decoratorInfo.ServiceTypeName,
 40755                    decoratorInfo.Order,
 40756                    assembly.Name,
 40757                    sourceFilePath));
 758            }
 759
 760            // Check for OpenDecoratorFor attributes (source-gen only open generic decorators)
 1797534761            var openDecoratorInfos = OpenDecoratorDiscoveryHelper.GetOpenDecoratorForAttributes(typeSymbol);
 3595082762            foreach (var openDecoratorInfo in openDecoratorInfos)
 763            {
 7764                var sourceFilePath = typeSymbol.Locations.FirstOrDefault()?.SourceTree?.FilePath;
 7765                openDecorators.Add(new DiscoveredOpenDecorator(
 7766                    openDecoratorInfo.DecoratorType,
 7767                    openDecoratorInfo.OpenGenericInterface,
 7768                    openDecoratorInfo.Order,
 7769                    assembly.Name,
 7770                    sourceFilePath));
 771            }
 772
 773            // Check for RegisterClosedOverImplementationsOf attributes (source-gen only composition markers)
 1797534774            var composedMarkerInfos = ComposedRegistrationDiscoveryHelper.GetComposedMarkers(typeSymbol);
 3595206775            foreach (var composedMarkerInfo in composedMarkerInfos)
 776            {
 69777                var sourceFilePath = typeSymbol.Locations.FirstOrDefault()?.SourceTree?.FilePath;
 69778                composedMarkers.Add(new DiscoveredComposedMarker(
 69779                    composedMarkerInfo.CompositionType,
 69780                    composedMarkerInfo.SourceOpenGenericInterface,
 69781                    composedMarkerInfo.AsServiceType,
 69782                    composedMarkerInfo.Lifetime,
 69783                    assembly.Name,
 69784                    sourceFilePath));
 785            }
 786
 787            // Check for Intercept attributes and collect intercepted services
 1797534788            if (InterceptorDiscoveryHelper.HasInterceptAttributes(typeSymbol))
 789            {
 15790                var lifetime = TypeDiscoveryHelper.DetermineLifetime(typeSymbol);
 15791                if (lifetime.HasValue)
 792                {
 15793                    var classLevelInterceptors = InterceptorDiscoveryHelper.GetInterceptAttributes(typeSymbol);
 15794                    var methodLevelInterceptors = InterceptorDiscoveryHelper.GetMethodLevelInterceptAttributes(typeSymbo
 15795                    var methods = InterceptorDiscoveryHelper.GetInterceptedMethods(typeSymbol, classLevelInterceptors, m
 796
 15797                    if (methods.Count > 0)
 798                    {
 15799                        var typeName = TypeDiscoveryHelper.GetFullyQualifiedName(typeSymbol);
 15800                        var interfaces = TypeDiscoveryHelper.GetRegisterableInterfaces(typeSymbol, compilation.Assembly)
 30801                        var interfaceNames = interfaces.Select(i => TypeDiscoveryHelper.GetFullyQualifiedName(i)).ToArra
 802
 803                        // Collect all unique interceptor types
 15804                        var allInterceptorTypes = classLevelInterceptors
 15805                            .Concat(methodLevelInterceptors)
 18806                            .Select(i => i.InterceptorTypeName)
 15807                            .Distinct()
 15808                            .ToArray();
 809
 15810                        var interceptedSourceFilePath = typeSymbol.Locations.FirstOrDefault()?.SourceTree?.FilePath;
 811
 15812                        interceptedServices.Add(new DiscoveredInterceptedService(
 15813                            typeName,
 15814                            interfaceNames,
 15815                            assembly.Name,
 15816                            lifetime.Value,
 15817                            methods.ToArray(),
 15818                            allInterceptorTypes,
 15819                            interceptedSourceFilePath));
 820                    }
 821                }
 822            }
 823
 824            // Check for injectable types (but skip types that are providers, which are handled separately)
 1797534825            if (TypeDiscoveryHelper.IsInjectableType(typeSymbol, isCurrentAssembly) && !ProviderDiscoveryHelper.HasProvi
 826            {
 827                // Determine lifetime first - only include types that are actually injectable
 504404828                var lifetime = TypeDiscoveryHelper.DetermineLifetime(typeSymbol);
 504404829                if (lifetime.HasValue)
 830                {
 287548831                    var interfaces = TypeDiscoveryHelper.GetRegisterableInterfaces(typeSymbol, compilation.Assembly);
 287548832                    var typeName = TypeDiscoveryHelper.GetFullyQualifiedName(typeSymbol);
 287985833                    var interfaceNames = interfaces.Select(i => TypeDiscoveryHelper.GetFullyQualifiedName(i)).ToArray();
 834
 835                    // Capture interface locations for navigation
 287548836                    var interfaceInfos = interfaces.Select(i =>
 287548837                    {
 437838                        var ifaceLocation = i.Locations.FirstOrDefault();
 437839                        var ifaceFilePath = ifaceLocation?.SourceTree?.FilePath;
 437840                        var ifaceLine = ifaceLocation?.GetLineSpan().StartLinePosition.Line + 1 ?? 0;
 437841                        return new InterfaceInfo(TypeDiscoveryHelper.GetFullyQualifiedName(i), ifaceFilePath, ifaceLine)
 287548842                    }).ToArray();
 843
 844                    // Check for [DeferToContainer] attribute - use declared types instead of discovered constructors
 287548845                    var deferredParams = TypeDiscoveryHelper.GetDeferToContainerParameterTypes(typeSymbol);
 846                    TypeDiscoveryHelper.ConstructorParameterInfo[] constructorParams;
 287548847                    if (deferredParams != null)
 848                    {
 849                        // DeferToContainer doesn't support keyed services - convert to simple params
 10850                        constructorParams = deferredParams.Select(t => new TypeDiscoveryHelper.ConstructorParameterInfo(
 851                    }
 852                    else
 853                    {
 854                        // [GenerateConstructor]/field-triggered types get their constructor
 855                        // emitted by a sibling generator pass this compilation can't see yet.
 856                        // Use the same field-derived model instead of the symbol-based
 857                        // constructor lookup, which would otherwise still see only the
 858                        // implicit parameterless constructor.
 287543859                        constructorParams = ConstructorGenerationDiscoveryHelper.TryGetEffectiveConstructorParameters(ty
 287543860                            ?? TypeDiscoveryHelper.GetBestConstructorParametersWithKeys(typeSymbol)?.ToArray() ?? [];
 861                    }
 862
 863                    // Get source file path and line for breadcrumbs (null for external assemblies)
 287548864                    var location = typeSymbol.Locations.FirstOrDefault();
 287548865                    var sourceFilePath = location?.SourceTree?.FilePath;
 287548866                    var sourceLine = location?.GetLineSpan().StartLinePosition.Line + 1 ?? 0; // Convert to 1-based
 867
 868                    // Get [Keyed] attribute keys
 287548869                    var serviceKeys = TypeDiscoveryHelper.GetKeyedServiceKeys(typeSymbol);
 870
 871                    // Check if this type implements IDisposable or IAsyncDisposable
 287548872                    var isDisposable = TypeDiscoveryHelper.IsDisposableType(typeSymbol);
 873
 287548874                    injectableTypes.Add(new DiscoveredType(typeName, interfaceNames, assembly.Name, lifetime.Value, cons
 875
 876                    // Every injectable type is a candidate implementation for [RegisterClosedOverImplementationsOf]
 877                    // expansion. Tying collection to the injectable-registration site means a composition composes
 878                    // over exactly the set Needlr registers — current assembly plus referenced libraries — so
 879                    // cross-assembly definitions are handled the same way decorators expand over injectable types.
 287548880                    composedCandidateTypes.Add(typeSymbol);
 881                }
 882            }
 883
 884            // Check for hosted service types (BackgroundService or IHostedService implementations)
 1797534885            if (TypeDiscoveryHelper.IsHostedServiceType(typeSymbol, isCurrentAssembly))
 886            {
 887                // Use the same field-derived model that drives constructor generation
 888                // when one applies, since the symbol-based lookup can't see the
 889                // sibling generator's constructor output within this compilation.
 10890                var effectiveGeneratedParams = ConstructorGenerationDiscoveryHelper.TryGetEffectiveConstructorParameters
 10891                var isGeneratedButNotInjectable = effectiveGeneratedParams is null &&
 10892                    ConstructorGenerationDiscoveryHelper.TryGetModel(typeSymbol) != null;
 893
 894                // A type eligible for constructor generation whose generated constructor
 895                // isn't fully container-resolvable (e.g. a field-triggered guard on a
 896                // plain string) must not fall back to the symbol-based scan below: that
 897                // scan only sees the implicit parameterless constructor that exists
 898                // before the sibling GeneratedConstructorGenerator pass runs, so it would
 899                // register `services.AddSingleton<T>()` for a hosted service whose real
 900                // (generated) constructor the container can never actually activate.
 901                // Skip automatic hosted registration entirely rather than emit metadata
 902                // — and a registration call — for an unactivatable worker.
 10903                if (!isGeneratedButNotInjectable)
 904                {
 9905                    var typeName = TypeDiscoveryHelper.GetFullyQualifiedName(typeSymbol);
 9906                    var constructorParams = effectiveGeneratedParams?.ToArray()
 9907                        ?? TypeDiscoveryHelper.GetBestConstructorParametersWithKeys(typeSymbol)?.ToArray() ?? [];
 9908                    var sourceFilePath = typeSymbol.Locations.FirstOrDefault()?.SourceTree?.FilePath;
 909
 9910                    hostedServices.Add(new DiscoveredHostedService(
 9911                        typeName,
 9912                        assembly.Name,
 9913                        GeneratorLifetime.Singleton, // Hosted services are always singleton
 9914                        constructorParams,
 9915                        sourceFilePath));
 916                }
 917            }
 918
 919            // Check for [Provider] attribute
 1797534920            if (ProviderDiscoveryHelper.HasProviderAttribute(typeSymbol))
 921            {
 20922                var discoveredProvider = ProviderDiscoveryHelper.DiscoverProvider(typeSymbol, assembly.Name, generatedNa
 20923                if (discoveredProvider.HasValue)
 924                {
 20925                    providers.Add(discoveredProvider.Value);
 926                }
 927            }
 928
 929            // Check for plugin types (concrete class with parameterless ctor and interfaces)
 1797534930            if (TypeDiscoveryHelper.IsPluginType(typeSymbol, isCurrentAssembly))
 931            {
 500086932                var pluginInterfaces = TypeDiscoveryHelper.GetPluginInterfaces(typeSymbol, compilation.Assembly);
 500086933                if (pluginInterfaces.Count > 0)
 934                {
 1858935                    var typeName = TypeDiscoveryHelper.GetFullyQualifiedName(typeSymbol);
 3730936                    var interfaceNames = pluginInterfaces.Select(i => TypeDiscoveryHelper.GetFullyQualifiedName(i)).ToAr
 1858937                    var attributeNames = TypeDiscoveryHelper.GetPluginAttributes(typeSymbol).ToArray();
 1858938                    var sourceFilePath = typeSymbol.Locations.FirstOrDefault()?.SourceTree?.FilePath;
 1858939                    var order = PluginOrderHelper.GetPluginOrder(typeSymbol);
 940
 1858941                    pluginTypes.Add(new DiscoveredPlugin(typeName, interfaceNames, assembly.Name, attributeNames, source
 942                }
 943            }
 944
 945        }
 110303946    }
 947
 948    private static string GenerateTypeRegistrySource(
 949        GeneratedRegistrationPlan registrationPlan,
 950        BreadcrumbWriter breadcrumbs,
 951        string? projectDirectory)
 952    {
 597953        var builder = new StringBuilder();
 597954        var discoveryResult = registrationPlan.DiscoveryResult;
 597955        var assemblyName = registrationPlan.AssemblyName;
 597956        var safeAssemblyName = GeneratorHelpers.SanitizeIdentifier(assemblyName);
 597957        var isAotProject = registrationPlan.IsAotProject;
 597958        var hasConfigBoundRegistrations =
 597959            registrationPlan.HasConfigBoundRegistrations;
 960
 597961        breadcrumbs.WriteFileHeader(builder, assemblyName, "Needlr Type Registry");
 597962        builder.AppendLine("#nullable enable");
 597963        builder.AppendLine();
 597964        builder.AppendLine("using System;");
 597965        builder.AppendLine("using System.Collections.Generic;");
 597966        builder.AppendLine();
 597967        if (hasConfigBoundRegistrations)
 968        {
 162969            builder.AppendLine("using Microsoft.Extensions.Configuration;");
 162970            if (isAotProject ||
 162971                registrationPlan.HasHttpClientRegistrations)
 972            {
 89973                builder.AppendLine("using Microsoft.Extensions.Options;");
 974            }
 975        }
 597976        builder.AppendLine("using Microsoft.Extensions.DependencyInjection;");
 597977        builder.AppendLine();
 597978        builder.AppendLine("using NexusLabs.Needlr;");
 597979        builder.AppendLine("using NexusLabs.Needlr.Generators;");
 597980        builder.AppendLine();
 597981        builder.AppendLine($"namespace {safeAssemblyName}.Generated;");
 597982        builder.AppendLine();
 597983        builder.AppendLine("/// <summary>");
 597984        builder.AppendLine("/// Compile-time generated registry of injectable types and plugins.");
 597985        builder.AppendLine("/// This eliminates the need for runtime reflection-based type discovery.");
 597986        builder.AppendLine("/// </summary>");
 597987        builder.AppendLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"NexusLabs.Needlr.Generators\", \"1
 597988        builder.AppendLine("public static class TypeRegistry");
 597989        builder.AppendLine("{");
 990
 597991        CodeGen.InjectableTypesCodeGenerator.GenerateInjectableTypesArray(builder, discoveryResult.InjectableTypes, brea
 597992        builder.AppendLine();
 597993        CodeGen.PluginsCodeGenerator.GeneratePluginTypesArray(builder, discoveryResult.PluginTypes, breadcrumbs, project
 994
 597995        builder.AppendLine();
 597996        builder.AppendLine("    /// <summary>");
 597997        builder.AppendLine("    /// Gets all injectable types discovered at compile time.");
 597998        builder.AppendLine("    /// </summary>");
 597999        builder.AppendLine("    /// <returns>A read-only list of injectable type information.</returns>");
 5971000        builder.AppendLine("    public static IReadOnlyList<InjectableTypeInfo> GetInjectableTypes() => _types;");
 5971001        builder.AppendLine();
 5971002        builder.AppendLine("    /// <summary>");
 5971003        builder.AppendLine("    /// Gets all plugin types discovered at compile time.");
 5971004        builder.AppendLine("    /// </summary>");
 5971005        builder.AppendLine("    /// <returns>A read-only list of plugin type information.</returns>");
 5971006        builder.AppendLine("    public static IReadOnlyList<PluginTypeInfo> GetPluginTypes() => _plugins;");
 1007
 5971008        if (hasConfigBoundRegistrations)
 1009        {
 1621010            builder.AppendLine();
 1621011            GenerateRegisterOptionsMethod(builder, discoveryResult.Options, discoveryResult.HttpClients, safeAssemblyNam
 1012        }
 1013
 5971014        if (registrationPlan.HasProviderRegistrations)
 1015        {
 181016            builder.AppendLine();
 181017            CodeGen.DecoratorsCodeGenerator.GenerateRegisterProvidersMethod(
 181018                builder,
 181019                registrationPlan.EmittedProviders,
 181020                safeAssemblyName,
 181021                breadcrumbs,
 181022                projectDirectory);
 1023        }
 1024
 5971025        builder.AppendLine();
 5971026        CodeGen.DecoratorsCodeGenerator.GenerateApplyDecoratorsMethod(builder, discoveryResult.Decorators, discoveryResu
 1027
 5971028        if (discoveryResult.ComposedRegistrations.Count > 0)
 1029        {
 431030            builder.AppendLine();
 431031            CodeGen.ComposedRegistrationsCodeGenerator.GenerateRegisterComposedTypesMethod(builder, discoveryResult.Comp
 1032        }
 1033
 5971034        if (discoveryResult.HostedServices.Count > 0)
 1035        {
 81036            builder.AppendLine();
 81037            CodeGen.DecoratorsCodeGenerator.GenerateRegisterHostedServicesMethod(builder, discoveryResult.HostedServices
 1038        }
 1039
 5971040        builder.AppendLine("}");
 1041
 5971042        return builder.ToString();
 1043    }
 1044
 1045    private static void GenerateRegisterOptionsMethod(StringBuilder builder, IReadOnlyList<DiscoveredOptions> options, I
 1046    {
 1621047        builder.AppendLine("    /// <summary>");
 1621048        builder.AppendLine("    /// Registers all discovered options types with the service collection.");
 1621049        builder.AppendLine("    /// This binds configuration sections to strongly-typed options classes,");
 1621050        builder.AppendLine("    /// and wires up named HttpClient registrations for [HttpClientOptions] types.");
 1621051        builder.AppendLine("    /// </summary>");
 1621052        builder.AppendLine("    /// <param name=\"services\">The service collection to configure.</param>");
 1621053        builder.AppendLine("    /// <param name=\"configuration\">The configuration root to bind options from.</param>")
 1621054        builder.AppendLine("    public static void RegisterOptions(IServiceCollection services, IConfiguration configura
 1621055        builder.AppendLine("    {");
 1056
 1621057        if (options.Count == 0 && httpClients.Count == 0)
 1058        {
 01059            breadcrumbs.WriteInlineComment(builder, "        ", "No options or HttpClient types discovered");
 1060        }
 1061        else
 1062        {
 1621063            if (options.Count > 0)
 1064            {
 1571065                if (isAotProject)
 1066                {
 831067                    CodeGen.OptionsCodeGenerator.GenerateAotOptionsRegistration(builder, options, safeAssemblyName, brea
 1068                }
 1069                else
 1070                {
 741071                    CodeGen.OptionsCodeGenerator.GenerateReflectionOptionsRegistration(builder, options, safeAssemblyNam
 1072                }
 1073            }
 1074
 1621075            if (httpClients.Count > 0)
 1076            {
 61077                CodeGen.HttpClientCodeGenerator.EmitHttpClientRegistrations(builder, httpClients);
 1078            }
 1079        }
 1080
 1621081        builder.AppendLine("    }");
 1621082    }
 1083
 1084}

Methods/Properties

Initialize(Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext)
GetBreadcrumbLevel(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider)
GetProjectDirectory(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider)
GetDiagnosticOptions(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider)
ShouldExportGraph(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider)
ShouldEmitRegistrationManifest(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider)
IsAotProject(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider)
GetAttributeInfoFromCompilation(Microsoft.CodeAnalysis.Compilation)
DiscoverTypes(Microsoft.CodeAnalysis.Compilation,System.String[],System.String[],System.Boolean)
CollectTypesFromAssembly(Microsoft.CodeAnalysis.IAssemblySymbol,System.Collections.Generic.IReadOnlyList`1<System.String>,System.Collections.Generic.IReadOnlyList`1<System.String>,System.Collections.Generic.List`1<NexusLabs.Needlr.Generators.Models.DiscoveredType>,System.Collections.Generic.List`1<NexusLabs.Needlr.Generators.Models.DiscoveredPlugin>,System.Collections.Generic.List`1<NexusLabs.Needlr.Generators.Models.DiscoveredDecorator>,System.Collections.Generic.List`1<NexusLabs.Needlr.Generators.Models.DiscoveredOpenDecorator>,System.Collections.Generic.List`1<NexusLabs.Needlr.Generators.Models.DiscoveredInterceptedService>,System.Collections.Generic.List`1<NexusLabs.Needlr.Generators.Models.DiscoveredFactory>,System.Collections.Generic.List`1<NexusLabs.Needlr.Generators.Models.DiscoveredOptions>,System.Collections.Generic.List`1<NexusLabs.Needlr.Generators.Models.DiscoveredHostedService>,System.Collections.Generic.List`1<NexusLabs.Needlr.Generators.Models.DiscoveredProvider>,System.Collections.Generic.List`1<NexusLabs.Needlr.Generators.Models.DiscoveredHttpClient>,System.Collections.Generic.List`1<NexusLabs.Needlr.Generators.Models.InaccessibleType>,System.Collections.Generic.List`1<NexusLabs.Needlr.Generators.Models.DiscoveredComposedMarker>,System.Collections.Generic.List`1<Microsoft.CodeAnalysis.INamedTypeSymbol>,Microsoft.CodeAnalysis.Compilation,System.Boolean,System.String)
GenerateTypeRegistrySource(NexusLabs.Needlr.Generators.Models.GeneratedRegistrationPlan,NexusLabs.Needlr.Generators.BreadcrumbWriter,System.String)
GenerateRegisterOptionsMethod(System.Text.StringBuilder,System.Collections.Generic.IReadOnlyList`1<NexusLabs.Needlr.Generators.Models.DiscoveredOptions>,System.Collections.Generic.IReadOnlyList`1<NexusLabs.Needlr.Generators.Models.DiscoveredHttpClient>,System.String,NexusLabs.Needlr.Generators.BreadcrumbWriter,System.String,System.Boolean)