Last week we run into a strange problem with our integration tests. On some developer machines everything worked fine, while other machines got errors like this one:
System.InvalidOperationException : Cannot resolve scoped service ‘my.application.IOrderRepository’ from root provider.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)
The problem
It took us hours to understand what was happening. We finally figured out that this was a problem with ReSharper 2023.3 that also happens with Rider. The source of the problem was this very simple and safe change that sets the environment variable DOTNET_ENVIRONMENT
to Development
:
Apparently, Microsoft.Extensions.Hosting
uses this variable when setting up the dependency injection container and turns on an additional validation when it is set to Development.
While this behaviour is great when you use the full DI configuration, it is a problem when you only use a part for your integration tests.
The solution
We use a different host builder for our integration tests. That allowed us to modify the behaviour and turn ValidateScopes (and ValidateOnBuild) off for our integration tests:
1 2 3 4 5 6 7 8 9 10 |
this.host = Host.CreateDefaultBuilder() .UseDefaultServiceProvider((_, options) => { options.ValidateOnBuild = false; options. ValidateScopes = false; }) .ConfigureServices(services => { services.AddOrderModule() ... |
With these 5 lines our integration tests worked on all machines independently if we had installed the newest version of ReSharper or not.
Parting thoughts
Once more a tiny safe change was not that safe after all. Therefore, make sure that you document even those safe changes; then when something goes wrong, your customers have at least a tiny chance to understand what happened.