Using ASP.NET Core 3 in .NET libraries
With the release of ASP.NET Core 3, Microsoft has also changed the way how to use and reference ASP.NET Core dependencies. In the past you could use NuGet to find the ASP.NET Core packages you needed.
For example, if you needed some interfaces or ASP.NET Core features like
Razor or some things like the
ViewFeatures, the csproj looked like this:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp2.2</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.ViewFeatures" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Razor" Version="2.2.0" /> </ItemGroup> </Project>
With ASP.NET Core 3.0, however, the way of referencing has fundamentally changed. If you try to search for NuGet packages with ASP.NET Core 3.0, you will notice that for many packages there was no new release for 3.x.
However, if you use these packages, you usually don't notice this when using them - but exceptions like "Method not found" appear, which let you know: something is wrong.
ASP.NET Core 3 - Runtime
ASP.NET Core 3.0 is a separate runtime and does not have to be explicitly specified in the csproj. It is sufficient to use the project
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp3.0</TargetFramework> </PropertyGroup> <ItemGroup> <!-- References like NuGet here --> </ItemGroup> </Project>
Microsoft.NET.Sdk.Web causes .NET to automatically know that this application can run. So an entry method
main() is necessary, but not suitable for libraries.
The solution in this case is to use the
FrameworkReference, which can unfortunately be found in this form inconspicuously in the migration notes.
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp3.0</TargetFramework> <!-- Enable C# 8 --> <LangVersion>8.0</LangVersion> <!-- Enable Nullable reference types --> <NullableContextOptions>enable</NullableContextOptions> </PropertyGroup> <ItemGroup> <!-- Reference ASP.NET Core 3 dependencies --> <FrameworkReference Include="Microsoft.AspNetCore.App" /> </ItemGroup> </Project>
If you were to use a
PackageReference here, following warning appears:
warning NETSDK1080: A PackageReference to Microsoft.AspNetCore.App is not necessary when targeting .NET Core 3.0 or higher. If Microsoft.NET.Sdk.Web is used, the shared framework will be referenced automatically. Otherwise, the PackageReference should be replaced with a FrameworkReference.