A good replacement for the InterfaceGenerator
Unit testing/Abstraction libraries
If you developed with .NET for a while, you probably already heard of, and used the InterfaceGenerator. This package contains a source generator which generates an interface when the [GenerateAutoInterface]
attribute is applied to a class in your project.
However, in order to follow the best practices concerning unit-testing, you should actually always move interfaces into an Abstractions library. For example Microsoft.AspNetCore.Routing has a corresponding Microsoft.AspNetCore.Routing.Abstractions library, which for the most part contains interfaces. Then in your unit-test projects you simply create mocks for these interfaces and add them to the service-container.
Since the implementation project (Microsoft.AspNetCore.Routing) has a project reference to the abstractions project (Microsoft.AspNetCore.Routing.Abstractions) and not the opposite way, you sadly can’t use the InterfaceGenerator like this. But don’t worry, there’s another way.
A better solution
We could however, build an analyzer + codefix which takes care of this. The analyzer looks for public members on your class, and checks if they’re present on the interface, which resides in the abstractions project within the same solution. Let’s just ask ChatGPT 😊
Oh well, a source generator can’t produce code in another project. Let’s suggest something:
After some more adjustments this is the code I ended up with:
The codefix in action
I created a simple test solution like this, with the analyzer package installed in the implementations project.
Result
The entire project is hosted here