Search code examples
c#asp.net-web-apinugetpostsharp

How to have PostSharp included in build process for ASP.NET WebApi project when installed using our own Nuget package?


We have a class library (C#, .NET 5) where we've added a reference to the PostSharp nuget-package (using PackageReference in our csproj-file) and implemented a PostSharp OnMethodBoundaryAspect. This class library is then packaged into a Nuget package to be consumed by our micro services/WebApi-projects.

When I add a reference to this nuget-package in one of our ASP.NET WebApi project I see that references to PostSharp and PostSharp.Redist are also being included along with our class library.

However, when adding the OnMethodBoundaryAspect to one of our functions in the WebApi-project the code in the aspect is not being executed. If I add a reference to PostSharp directly in the WebApi-project it works just fine.

How do I make sure that PostSharp is being included in the build process in our WebApi-project when it is being included from our own Nuget-package?

This answer to another question (https://stackoverflow.com/a/68470518/182380) on StackOverflow mentions that PostSharp.targets needs to be included in the build process and installing the PostSharp nuget-package will make this happen, but what if I want to include PostSharp from our own Nuget-package and have it included in the build process of the WebApi-project that way, how do I go about fixing that?


Solution

  • This is a result of NuGet's behavior of project references (build-time parts of the package are not taken from referenced projects).

    For your own package, it should be enough to have a dependency (in the .nuspec file or appropriately configured csproj) on PostSharp package, which would then include all PostSharp package assets in the project where you've referenced your package (this is the default behavior of NuGet dependency if you don't specify any includeAssets and excludeAssets).

    In case of PackageReference in your project file, you also need to set privateAssets to none, because the default behavior is Build,Analyzers:

    <PackageReference Include="PostSharp" Version="6.9.9" PrivateAssets="none" />