For one of my clients, I maintain a set of libraries that help to streamline the development of new applications in .NET Core. The functionality offered through these libraries follow the 'paved road' principle and help the development teams to fall in the pit of success. They are used by multiple development teams working on different projects.
As a library author, I don’t have full control on all the different ways these libraries are used so I have to be very conscious in avoiding breaking changes. In this post I want to share some details on how I try to manage and avoid breaking changes.
Microsoft.CodeAnalysis.PublicApiAnalyzers
The ‘magic’ solution I use to avoid or handle breaking changes is with the help of a specific Roslyn analyzer, the Microsoft.CodeAnalysis.PublicApiAnalyzers.
Let me explain how this analyzer works.
First add a package reference to Microsoft.CodeAnalysis.PublicApiAnalyzers to your project:
dotnet add package Microsoft.CodeAnalysis.PublicAnalyzers
This will add 2 extra files to your project:
- PublicAPI.Shipped.txt
- PublicApi.Unshipped.txt
When you now try to build your project, you get a RS0016
diagnostics on all your public APIs:
You can now use the code fix feature to add the API to the PublicAPI.Unshipped.txt file:
Remark: In Visual Studio, you can apply the fix in one go for all changes.
It is up to you as a library author when you release a new version of your library to copy the changes from the PublicAPI.Unshipped.txt file to the PublicAPI.Shipped.txt file.
Remark: While preparing this post, I stumbled over an alternative solution, PublicApiGenerator, mentioned in a blog post by Andrew Lock. If you have experience using this package, please let me now.
More information
NuGet Gallery | Microsoft.CodeAnalysis.PublicApiAnalyzers 3.3.4
Preventing breaking changes in public APIs with PublicApiGenerator