How to remove reference to unused assembly inside Dependencies/Frameworks/Microsoft.NETCore.App?

Viewed 806

There're assemblies inside .NET 6 framework which I'm 100% sure I'll never use, however they still appear in the list of dependencies, ReSharper (and likely bare VS as well) still suggests them when importing types, and in general their existence is annoying.

For example, I'm 100% sure I'll never use Microsoft.Win32.Registry or System.Drawing, yet when writing Color I see IDE suggesting types I can't really use. I'm abandoning my Windows-only ways and I want to never see these again.

I tried pressing Delete after selecting the node, nothing happened. I tried adding <Reference Remove="System.Drawing" /> to my .csproj file, nothing happened. I tried using "Remove unused references", nothing happened.

Question: Is there any way to get rid of these references? Removing them from the list would be perfect, but just hiding them from suggestions of VS/R# would be fine too.

I've found multiple questions regarding removing references on SO, but they all seem to be about .NET 4.x, about adding an alternative, all this not being useful for my case.

VS2022 17.0.1, R# 2021.3 EAP, .NET 6.0, latest everything.

2 Answers

You cannot remove it there, but after your project is built you can "treeshake" all unused parts with some tools. Most obfuscators have a function for that purpose and I believe ILMerge also has a switch to trim unused types (Edit: no it does not).

Note that if you use reflection allot, you risk getting TypeLoadException's when types are removed that have no static reference but are always loaded dynamically through reflection. Using the attribute [ObfuscationAttribute(Exclude=true)] from these classes may help but actually the attribute has no specific property to prevent the class from being removed (only the attribute itself). Specific obfuscators will have their own options or features to prevent pruning.

In .Net 6 you can use Visual Studio to publish your project to a folder, choose self-contained and in the file publishing options you will find "produce single file". This will try to prune any unused (framework) assemblies. It will not prune unused classes in used assemblies.

If you want to prevent the unwanted options to show up in Intellisense, I guess you are out of luck. You could use an older version of visual studio that would only show items available in the defined scope (referenced in the project and in the using list of your namespace or class). I personally find the newer intellisense suggestions helpful, it saves me looking up the namespace and assembly name when I only remember the classname.

Related