sdk: Make ImplicitUsings does not work out of the box with .NET Framework project
Apologies if this is not the right repo! Reporting here because there are at least some issues in this repo referencing <ImplicitUsings>
Is your feature request related to a problem? Please describe.
Whenever I create a new class library project, it defaults to setting <ImplicitUsings>enable</ImplicitUsings>
. This is good. However, when I multi-target or re-target the project to hit .NET Framework, I get the following compiler error:
The type or namespace name ‘Http’ does not exist in the namespace ‘System.Net’ (are you missing an assembly reference?)
This can be resolved by adding a framework reference, but it would be nice if it “just worked”.
Describe the solution you’d like
I’d like for this to “just work” out of the box. One easy way to do this would be to change the generated usings file (ProjectName.GlobalUsings.g.cs) to look like the following:
// <auto-generated/>
global using global::System;
global using global::System.Collections.Generic;
global using global::System.IO;
global using global::System.Linq;
global using global::System.Net.Http;
global using global::System.Threading;
global using global::System.Threading.Tasks;
// new addition
#if NETFRAMEWORK
namespace System.Net.Http { }
#endif
Potentially we could define all the referenced namespaces to ensure that the auto-generated code never gives an error regardless of what framework is targeted and what references are imported.
Additional context
Example .csproj to reproduce the issue:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net472;netstandard2.0;net6.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>10</LangVersion>
</PropertyGroup>
</Project>
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Reactions: 4
- Comments: 16 (6 by maintainers)
Commits related to this issue
- Make the ImplicitUsings feature minimally define each imported namespace to avoid compilation errors based on target framework. Fix #24909 — committed to madelson/dotnet-sdk by madelson 2 years ago
- #24909 Add condition for System.NET.http to work for Multitargeting .NETFramework (#32630) — committed to dotnet/sdk by JL03-Yue a year ago
At minimum, we should condition the Using for System.Net.Http so that it is only added for TFMs that natively include the reference to System.Net.Http. Perhaps it’s safe enough to use .NET Standard2.0+, .Net Core 3.1, and .Net 5+? This condition would need to be added here
resolved in #32630
Yes, thanks for bringing this to my attention. We should attempt to dedupe these items as a mitigation.
Rather than adding empty namespaces, I think what we probably want to do here is add conditions to where they are added to MSBuild:
lol, i take alot hours with project not using http request but error at
system.net.http