awslabs / aws-dotnet-messaging

An AWS-native framework that simplifies the development of .NET message processing applications that use AWS services, such as SQS, SNS, and EventBridge.
https://awslabs.github.io/aws-dotnet-messaging/
Apache License 2.0
68 stars 11 forks source link

Type parameters should be decorated with DynamicallyAccessedMembersAttribute #144

Open NoahStolk opened 1 month ago

NoahStolk commented 1 month ago

Describe the feature

The MessageBusBuilder class exposes various methods that accept Type instances or type parameters that are used to dynamically construct instances of said types. For example, in the MessageBusBuilder.AddMessageHandler method, the THandler type is used to dynamically construct an instance of that type.

This can and should be indicated by adding DynamicallyAccessedMembersAttribute to the type parameter. This allows tools such as ReSharper to detect that this type is created dynamically. Adding this attribute would also prevent code from being trimmed/removed incorrectly when compiling to native code using Native AOT.

Use Case

Currently, ReSharper complains that my handler type is never constructed and should be removed because it is seen as "dead code". I also believe (but have not yet tested this) that my handler type would be removed if I enabled trimming or compiled my application to native code using Native AOT, which would cause runtime exceptions. There are various workarounds for this, but the obvious fix would be to just include the attribute here.

Proposed Solution

Add the attribute where necessary. Example usages of the attribute can be found in the ASP.NET Core runtime. For example, AddSingleton, AddScoped, and AddTransient use this attribute:

public static IServiceCollection AddSingleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services)
    where TService : class
    where TImplementation : class, TService
// ...

public static IServiceCollection AddSingleton(
    this IServiceCollection services,
    [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType)
// ...

Other Information

No response

Acknowledgements

AWS.Messaging (or related) package versions

AWS.Messaging 0.9.1

Targeted .NET Platform

.NET 8

Operating System and version

Windows 11

ashishdhingra commented 4 weeks ago

Needs review with the team.

ashishdhingra commented 3 weeks ago

@NoahStolk Thanks for the issue report. We have a larger effort in our internal backlog to make this library NativeAOT compatible. This is one the the things we would consider. Related discussion https://github.com/awslabs/aws-dotnet-messaging/discussions/109.