Skip to content

ILLink Trim Analyzer not warning for TryAddSingleton #68420

Open

Description

Using a recent .NET 8 SDK, build the following project

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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <PublishAot>true</PublishAot>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0-preview.4.23259.5" />
  </ItemGroup>

</Project>
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

var services = new ServiceCollection();
services.AddService<MyService>();

record MyService;

static class Extensions
{
    public static void AddService<TService>(this ServiceCollection services)
        where TService : class
    {
        services.TryAddSingleton<TService>();
    }
}

You should get a warning from the trimming analyzer because AddService<TService> isn't annotated to preserve the constructors of TService, however it calls services.TryAddSingleton<TService>(); which IS annotated with a DynamicallyAccessedMembers attribute. So the analyzer should be able to give a warning here during build, but doesn't.

Now dotnet publish the app, and now you get the warning:

C:\Users\eerhardt\source\repos\ConsoleApp90\ConsoleApp90\Program.cs(16): Trim analysis warning IL2091: Extensions.AddService<TService>(ServiceCollection):
 'TService' generic argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors' in 'Microsoft.Extensions.DependencyInjection.Extensions.
ServiceCollectionDescriptorExtensions.TryAddSingleton<TService>(IServiceCollection)'. The generic parameter 'TService' of 'Extensions.AddService<TService>
(ServiceCollection)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target loca
tion it is assigned to. [C:\Users\eerhardt\source\repos\ConsoleApp90\ConsoleApp90\ConsoleApp90.csproj]

The analyzer needs to catch this warning so libraries that are depending on it for warnings know they have a trimming issue here.

cc @agocke @vitek-karas @sbomer

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

Metadata

Assignees

Type

No type

Projects

  • Status

    No status

Relationships

None yet

Development

No branches or pull requests

Issue actions