Skip to content

[API Proposal] Typed factory attributes for type-map activation - #137006

Draft
pavelsavara wants to merge 1 commit into
jsexport-typemap-assembly-lazyfrom
type-map-factory
Draft

pavelsavara wants to merge 1 commit into
jsexport-typemap-assembly-lazyfrom
type-map-factory

Conversation

@pavelsavara

@pavelsavara pavelsavara commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Purpose and staging

API prototype for discussion; not merge-ready. Explore a generalized, typed factory attribute for activating instances discovered through type maps, rather than adding a JSExport-specific activation attribute.

This draft is stacked on #136924, targeting its jsexport-typemap-assembly-lazy branch so the diff contains only the factory mechanism and its adoption. The intended landing is a separate staged follow-up after the JSExport work, only if the generalized design passes discussion and API review. The factory APIs below are not included in the existing JSExport API approval.

Problem

An external type map returns a Type, but does not convey a constructor requirement or prescribe activation. JSExport currently uses Activator.CreateInstance(Type), a constructor DynamicDependency, and an IL2067 suppression. This is a general activation gap: discovery and trim-safe construction are separate responsibilities.

An optional factory attribute lets the consumer retrieve a factory using its known contract, while the implementation type and new() constraint are encoded where the implementation is declared.

Proposed API

New public types in System.Runtime.InteropServices, extracted from the built implementation with GenAPI:

namespace System.Runtime.InteropServices;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
public abstract class TypeMapFactoryAttribute<TContract> : Attribute
{
    protected TypeMapFactoryAttribute();
    public abstract TContract CreateInstance();
}

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
public sealed class TypeMapFactoryAttribute<TContract, TImplementation>
    : TypeMapFactoryAttribute<TContract>
    where TImplementation : TContract, new()
{
    public TypeMapFactoryAttribute();
    public override TContract CreateInstance();
}

The concrete factory calls new TImplementation() for every CreateInstance() invocation. It does not cache instances. The abstract base enables typed attribute lookup without knowing the implementation type.

Prototype: 42f17e4.

General usage

using System;
using System.Reflection;
using System.Runtime.InteropServices;

public interface IService { }
public sealed class Service : IService { }

[TypeMapFactory<IService, Service>]
public sealed class ServiceDescriptor { }

public static class Consumer
{
    // mappedType comes from the consumer's existing concrete type-map group.
    public static IService Create(Type mappedType)
    {
        TypeMapFactoryAttribute<IService>? factory =
            mappedType.GetCustomAttribute<TypeMapFactoryAttribute<IService>>(inherit: false);
        if (factory is null)
            throw new InvalidOperationException("The mapped type has no IService factory.");

        return factory.CreateInstance();
    }
}

The mapped descriptor need not be the implementation itself. The API does not:

  • Register type-map entries, replace TypeMapAttribute, or alter type-map traversal.
  • Add enumeration or impose new() on existing maps.
  • Define a singleton, lifetime, disposal, or dependency-injection policy.
  • Wrap the type-map intrinsic in a generic discovery helper: the group remains statically known at the consumer's lookup site.

JSExport adoption as evidence

The generator adds this annotation to its existing provider:

[TypeMapFactory<JSExportProvider, __GeneratedJSExportProvider>]

The host retrieves TypeMapFactoryAttribute<JSExportProvider> from the mapped provider type and invokes CreateInstance(). This removes the opaque Activator.CreateInstance(Type) call, its IL2067 suppression, and the generated provider-constructor DynamicDependency. Missing factory metadata is an explicit error, not a silent fallback.

Lookup to provider instance

The host's activation path is shown below (surrounding partial class omitted). s_exportProviders caches TypeMapping.GetOrCreateExternalTypeMapping<JSExportProvider>(); its values are mapped provider types, not provider instances:

private static bool TryBindMappedAssemblyExports(string assemblyName)
{
    if (!s_exportProviders.Value.TryGetValue(assemblyName, out Type? providerType))
        return false;

    TypeMapFactoryAttribute<JSExportProvider>? factory =
        providerType.GetCustomAttribute<TypeMapFactoryAttribute<JSExportProvider>>(
            inherit: false);
    if (factory is null)
        throw new InvalidOperationException(
            SR.Format(SR.JSExportProviderMissingFactory, providerType));

    JSExportProvider provider = factory.CreateInstance();

    JavaScriptImports.RegisterLazyCSFunctions(
        assemblyName, provider.GetExportNames().ToArray(), provider.Bind);
    return true;
}

For the annotated __GeneratedJSExportProvider, the returned attribute object has concrete type TypeMapFactoryAttribute<JSExportProvider, __GeneratedJSExportProvider>. It is accessed through the single-argument base type, so the host does not need to name the generated implementation.

The concrete attribute supplies this override:

// Inside TypeMapFactoryAttribute<TContract, TImplementation>,
// where TImplementation : TContract, new():
public override TContract CreateInstance() => new TImplementation();

Thus factory.CreateInstance() constructs a fresh __GeneratedJSExportProvider and returns it as JSExportProvider. The new() constraint carries the public-constructor requirement to the trimmer. Discovery can then call GetExportNames() and retain the instance's Bind delegate; method binding still waits for the first JS invocation.

The independent IL2026 suppression on the concrete type-map lookup is also removed: that call is a recognized intrinsic. The new attribute is not presented as a general solution to RequiresUnreferencedCode.

The approved JSExportProvider public API, raw catalog transport, lazy per-method binding, aliases, legacy binary fallback, and runtime lifetime behavior remain unchanged.

Discussion / alternatives

  • Should this activation contract live in the general type-map category, or remain JSExport-specific? JSExport is the motivating production consumer; this prototype does not claim another production adoption site.
  • Is the abstract generic attribute the right lookup contract, or should a common interface represent factories?
  • Should supported targets include structs as in this sketch, or be restricted to classes?
  • Should one mapped type support multiple factory contracts, or retain the current non-repeatable attribute policy?
  • Retain the current constructor root/suppression instead: no new public API, but activation remains consumer-specific and manually justified.
  • Annotate map results with constructor requirements: this would constrain all map consumers, including those that do not construct instances. The optional attribute avoids that change.
  • A handwritten per-subsystem factory is viable; the question is whether the shared typed adapter is useful enough to standardize.

No size, startup, or throughput improvement is claimed. Attribute lookup still uses reflection; the benefit under discussion is explicit, analyzable constructor rooting and a reusable activation contract.

The JSExport adoption changes its generated-provider activation handshake: handwritten providers must also carry factory metadata. Existing .NET 10/.NET 11 generated assemblies retain their legacy path. New attribute-using binaries require the new API; this is one reason the change is staged separately.

Adoption scope

Site Change
JSExport generator and source snapshots Add the general factory annotation; remove provider constructor DynamicDependency.
JSExport managed host Use typed factory activation instead of opaque-Type activation and its suppression.
Counting provider / Wasm.Build.Tests Exercise real trimmed factory metadata, constructor retention, exact activation order, and existing lazy exports.
General interop attribute tests Non-JS contracts and separate descriptor/implementation types verify typed lookup, fresh instances, wrong-contract lookup, and non-inheritance.

Other in-tree type-map usages found are map-behavior/trimming tests, not additional production activation consumers. Proxy maps and COM-specific static details/lifetime contracts are intentionally not converted.

Validation also required a narrow test-setup correction: the Mono no-workload fixture previously selected the SDK-default daily runtime despite pinning the targeting pack. These two JSExport tests now opt into the existing current-runtime/current-WebAssembly-SDK override mechanism. This is necessary to test factory APIs that do not exist in the downloaded runtime; it does not change other test lanes.

Validation

Windows browser-wasm, Debug runtimes:

  • General factory tests: 5 passed on each VM, including separate descriptors, self-referencing/file-local implementation types, fresh instances, wrong-contract lookup and non-inheritance.
  • Generator: 46 passed, zero failed/skipped; generated output no longer has the provider constructor DynamicDependency.
  • Browser provider/legacy compatibility: CoreCLR 7 passed; Mono 6 passed, zero failed/skipped. Includes real trimmed attribute/factory/constructor retention and unchanged .NET 10/.NET 11 RC1 binaries. CoreCLR also covers untrimmed publication.
  • Full JS interop: CoreCLR 518 total / 516 passed / 2 existing skips; Mono 514 total / 511 passed / 3 existing skips; zero failures.
  • Source/reference/non-browser builds, CoreCLR staging, full Mono build, fresh reference/SDK packages and GenAPI passed. Generated API declarations match the curated reference surface; git diff --check passed.

Successful Mono provider tests were checked to resolve 12.0.0-dev, not the SDK-default daily runtime. Temporary diagnostics were removed before final validation. These two fixture scenarios use a bounded 60s startup allowance after intermittent failures at the harness's default 10s under shared-machine load; all behavioral assertions and exit-code checks remain in place.

NativeAOT, mobile, multithreaded configurations and non-Windows execution were not validated. No performance measurements are claimed.

Validation commands and results

Clean CoreCLR baseline and final CoreCLR staging — passed, zero warnings/errors:

.\build.cmd -bl -os browser -subset clr+libs+host -c Debug /p:RuntimeFlavor=CoreCLR /p:EnableHotReloadInRuntimeConfigDevFile=false
.\build.cmd -bl -os browser -subset libs.sfx+libs.native+host.native+libs.pretest -c Debug /p:RuntimeFlavor=CoreCLR /p:EnableHotReloadInRuntimeConfigDevFile=false

Mono build and final clean managed/runtime staging — passed, zero warnings/errors:

.\build.cmd -bl -os browser -subset mono+libs -c Debug /p:RuntimeFlavor=Mono /p:EnableHotReloadInRuntimeConfigDevFile=false
.\build.cmd -bl -os browser -subset libs.sfx+libs.pretest -c Debug /p:RuntimeFlavor=Mono /p:EnableHotReloadInRuntimeConfigDevFile=false

Generator — 46 passed:

.\dotnet.cmd build -bl /p:TargetOS=windows /p:TargetArchitecture=x64 /p:Configuration=Debug /p:RuntimeFlavor=CoreCLR /p:UseDefaultTestHost=true /p:UseLocalTargetingRuntimePack=false /p:NetCoreAppCurrentTestHostPath=D:\.dotnet /t:Test src\libraries\System.Runtime.InteropServices.JavaScript\tests\JSImportGenerator.UnitTest\JSImportGenerator.Unit.Tests.csproj

General factory tests — 5 passed per VM:

.\dotnet.cmd build -bl /p:TargetOS=browser /p:TargetArchitecture=wasm /p:Configuration=Debug /p:RuntimeFlavor=CoreCLR /t:Test /p:Scenario=WasmTestOnChrome /p:InstallChromeForTests=false /p:XUnitClassName=System.Runtime.InteropServices.Tests.TypeMapFactoryAttributeTests src\libraries\System.Runtime.InteropServices\tests\System.Runtime.InteropServices.UnitTests\System.Runtime.InteropServices.Tests.csproj
.\dotnet.cmd build -bl /p:TargetOS=browser /p:TargetArchitecture=wasm /p:Configuration=Debug /p:RuntimeFlavor=Mono /t:Test /p:Scenario=WasmTestOnChrome /p:InstallChromeForTests=false /p:XunitShowProgress=true /p:XUnitClassName=System.Runtime.InteropServices.Tests.TypeMapFactoryAttributeTests src\libraries\System.Runtime.InteropServices\tests\System.Runtime.InteropServices.UnitTests\System.Runtime.InteropServices.Tests.csproj

Provider and legacy cases — CoreCLR 7 passed; Mono 6 passed. A final Mono provider-only run after the startup allowance change passed both configurations:

.\dotnet.cmd build -bl /p:TargetOS=browser /p:TargetArchitecture=wasm /p:Configuration=Debug /p:RuntimeFlavor=CoreCLR /t:Test /p:TestUsingWorkloads=false /p:InstallWorkloadForTesting=false /p:InstallChromeForTests=false /p:XUnitClassName=Wasm.Build.Tests.LibraryInitializerTests src\mono\wasm\Wasm.Build.Tests
.\dotnet.cmd build -bl /p:TargetOS=browser /p:TargetArchitecture=wasm /p:Configuration=Debug /p:RuntimeFlavor=Mono /t:Test /p:TestUsingWorkloads=false /p:InstallWorkloadForTesting=false /p:InstallChromeForTests=false /p:XUnitClassName=Wasm.Build.Tests.LibraryInitializerTests src\mono\wasm\Wasm.Build.Tests
.\dotnet.cmd build -bl /p:TargetOS=browser /p:TargetArchitecture=wasm /p:Configuration=Debug /p:RuntimeFlavor=Mono /t:Test /p:TestUsingWorkloads=false /p:InstallWorkloadForTesting=false /p:InstallChromeForTests=false /p:XUnitMethodName=Wasm.Build.Tests.LibraryInitializerTests.JSExportFromAssemblyProvider src\mono\wasm\Wasm.Build.Tests

Full JS interop — CoreCLR 516 passed / 2 existing skips; Mono 511 passed / 3 existing skips, zero failures:

.\dotnet.cmd build -bl /p:TargetOS=browser /p:TargetArchitecture=wasm /p:Configuration=Debug /p:RuntimeFlavor=CoreCLR /t:Test /p:Scenario=WasmTestOnChrome /p:InstallChromeForTests=false /p:XunitShowProgress=true src\libraries\System.Runtime.InteropServices.JavaScript\tests\System.Runtime.InteropServices.JavaScript.UnitTests\System.Runtime.InteropServices.JavaScript.Tests.csproj
.\dotnet.cmd build -bl /p:TargetOS=browser /p:TargetArchitecture=wasm /p:Configuration=Debug /p:RuntimeFlavor=Mono /t:Test /p:Scenario=WasmTestOnChrome /p:InstallChromeForTests=false /p:XunitShowProgress=true src\libraries\System.Runtime.InteropServices.JavaScript\tests\System.Runtime.InteropServices.JavaScript.UnitTests\System.Runtime.InteropServices.JavaScript.Tests.csproj

GenAPI — passed, using a session-local GenAPITargetPath:

.\dotnet.cmd msbuild -bl /p:TargetOS=browser /p:TargetArchitecture=wasm /p:Configuration=Debug /p:RuntimeFlavor=CoreCLR /t:GenerateReferenceAssemblySource /p:GenAPITargetPath=C:\Users\pavelsavara\.copilot\session-state\64027cae-b9c4-4832-b675-ba5a473b2183\files\factory-generated-api.cs src\libraries\System.Runtime.InteropServices\src\System.Runtime.InteropServices.csproj

Tests inherited EnableHotReloadInRuntimeConfigDevFile=false for an unrelated SDK tooling issue and used a cached matching Chrome/ChromeDriver pair. Repository-managed test SDKs and targeting packs were provisioned; repository SDK pins and the shared SDK installation were not patched.

Note

This prototype and description were prepared with GitHub Copilot.

Provide a generic contract attribute and a new()-constrained implementation
adapter without changing type-map discovery or entry semantics.

Adopt the factory in generated JSExport providers and replace opaque-Type
activation, its warning suppression and manual constructor roots. Validate
general contracts and trimmed activation on CoreCLR and Mono.

Select the built Mono runtime and SDK in the JSExport test fixtures so the
prototype is exercised instead of the SDK-default daily runtime.

Co-authored-by: Copilot <[email protected]>
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 4 pipeline(s).
11 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/interop-contrib
See info in area-owners.md if you want to be subscribed.

@pavelsavara

Copy link
Copy Markdown
Member Author

cc @jkoritzinsky , I'm not sure it's worth it ...

@jkoritzinsky

jkoritzinsky commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Alternatively, can we put DynamicallyAccesedMembersAttribute(PublicConstructors) on the JSExportProvider base type?

I'd like to set this up to be trim-safe without suppressions, but I'm fine with whatever approach gives us that.

DynamicDependency is meant for "we cannot represent this in a trim-safe way without breaking API compat". We shouldn't be designing a new API that isn't trim-safe by design.

@pavelsavara

pavelsavara commented Nov 9, 2026 •

Copy link
Copy Markdown
Member Author

Alternatively, can we put DynamicallyAccesedMembersAttribute(PublicConstructors) on the JSExportProvider base type?

That would not work, the parent class JSExportProvider is not same target as inherited generated class __GeneratedJSExportProvider and it's constructor. Unless we change how ILLink works, option 5 below.

@pavelsavara

Copy link
Copy Markdown
Member Author

1. Current PR: explicit preservation + Activator

[DynamicDependency(
    DynamicallyAccessedMemberTypes.PublicParameterlessConstructor,
    typeof(GeneratedProvider))]
// On a reachable generated method.
var provider = (JSExportProvider)Activator.CreateInstance(mappedType)!;

Requires a trimming suppression and coordinated generator behavior.

2. JSExport-specific factory attribute

[GeneratedFactory]
class GeneratedProvider : JSExportProvider { /* ... */ }

class GeneratedFactoryAttribute : JSExportProviderAttribute
{
    public override JSExportProvider CreateInstance()
        => new GeneratedProvider();
}

Host retrieves the attribute and invokes its factory. Adds a generated factory type.

3. General factory attribute — #137006

[TypeMapFactory<JSExportProvider, GeneratedProvider>]
class GeneratedProvider : JSExportProvider { /* ... */ }
var provider = mappedType.GetCustomAttribute<
    TypeMapFactoryAttribute<JSExportProvider>>()!.CreateInstance();

Reusable factory API; concrete implementation executes new TImplementation().

4. Factory-capable type maps

[assembly: TypeMap<JSExportProvider, GeneratedProvider>("ExampleApp")]
// Proposed activation API:
TypeMapping.TryCreateInstance<JSExportProvider>(
    assembly, "ExampleApp", out var provider);

Requires new API and runtime/trimmer support for callable factories.

5. Extend type-map trimming/dataflow semantics

[DynamicallyAccessedMembers(
    DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
public abstract class JSExportProvider { /* ... */ }

Teach tooling to preserve mapped constructors and convey that guarantee to activation. Annotation alone is insufficient today. Potentially no new public API.

6. Generated factory registration

[ModuleInitializer]
internal static void Register()
    => Registry.Register(
        typeof(GeneratedProvider).Assembly,
        static () => new GeneratedProvider());

Host invokes the registered factory. Direct construction, but changes bootstrap architecture and requires module initialization.

A 6b variant uses an opaque runtime condition to retain a dormant new GeneratedProvider() instead. That only roots the constructor; Activator and its warning remain.

7. Provider is itself an attribute

public abstract class JSExportProvider : Attribute { /* ... */ }

[GeneratedProvider]
internal sealed class GeneratedProvider : JSExportProvider
{
    public GeneratedProvider() { }
    // Catalog and Bind overrides.
}
var provider =
    mappedType.GetCustomAttribute<JSExportProvider>(inherit: false)!;

One generated type; supported attribute construction replaces Activator. Needs API-review agreement and trimmed validation.

8. Empty module initializer + constructor dependency

Adapt main’s existing preservation pattern:

[ModuleInitializer]
[DynamicDependency(
    DynamicallyAccessedMemberTypes.PublicParameterlessConstructor,
    typeof(GeneratedProvider))]
internal static void PreserveProvider()
{
}
var provider = (JSExportProvider)Activator.CreateInstance(mappedType)!;

Explicitly roots the constructor without executing construction or registering a factory. Still needs the activation suppression.

Difference from 1: same preservation mechanism, but 8 gives it a dedicated, unconditionally reachable module-initializer anchor, matching main’s architecture rather than attaching the dependency to another generated method.

@jkoritzinsky

Copy link
Copy Markdown
Member

I don't like the generalized factory option as the type map explicitly doesn't guarantee any particular trimming preservation. I think a JS-specific factory (that would allow you the flexibility to change the requirements in the future) would be better than a generalized one.

I would also like option 5, but yeah there's still a warning you'd need to suppress as the trimmer's analysis can't see that the constructor will be preserved.

So either option 2 or option 5 would be my preference (I think option 2 is worth bringing to API review to see what they think as that's the pattern we've specifically guided people to use when doing type-map work).

@jkoritzinsky

Copy link
Copy Markdown
Member

Ok I looked more into option 5 and it seems that it doesn't quite work the way I thought it did (EventSource, the main user, has other special-casing around it). So option 2 is my preference.

@NinoFloris

Copy link
Copy Markdown
Contributor

We ran into this in the Npgsql prototype as well. We currently use a zero-sized struct implementing an interface and allocate it with RuntimeHelpers.Box, since structs are always allocatable, precisely for this API. A derived attribute impl referenced on a stub class would be the most conventional way to do it, but that requires two new types per entry.

With that in mind, option 5 doesn't really solve the problem for us, or for future users who run into the same issue.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants