Is there a way to mark usage of a type as "weak" (meaning it does not count unless there are other usages)?

Answered

Consider this example:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Example;

var host = Host
    .CreateDefaultBuilder(args)
    .ConfigureServices(serviceCollection =>
        serviceCollection.AddSingleton<ITest, Test>()
    )
    .Build();

// host.Services.GetRequiredService<ITest>().Method();

namespace Example
{
    public interface ITest
    {
        public void Method();
    }

    public class Test : ITest
    {
        public void Method()
        {
            Console.WriteLine("Method called");
        }
    }
}

Technically, the interface `ITest` is being used, but from the developer's perspective it's not. It's being registered in the DI container and never retrieved from there, because `GetRequiredService` is commented out.

Is there a way to mark the type parameter on `AddSingleton` and similar methods so that it only counts as a "weak" usage?

This would mean that if we uncomment the line with `GetRequiredService`, the interface would be marked as used, but if we leave it commented, the interface would be marked as "not used" by the code analysis.

This would come handy for other scenarios as well, like test suites and so on, like suggested here:

https://resharper-support.jetbrains.com/hc/en-us/community/posts/206669805-a-way-to-mark-usages-of-members-types-as-unimportant?input_string=Is%20there%20a%20way%20to%20mark%20usage%20of%20a%20class

1 comment
Comment actions Permalink

Hello Alex Bolenok, thank you for your question.

Unfortunately at this time, we do not have such an option. I have created a feature request in our bug tracker: https://youtrack.jetbrains.com/issue/RSRP-488455. Please feel free to comment or vote for it to get notifications about status changes. Thank you!

0

Please sign in to leave a comment.