© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
69 replies
Savage

✅ Problems with mocking a ServiceProvider

So, for an integration test I want to create a substitute for the general service provider my application uses.
The service provider is used to create a scope in a constructor/ factory.

This is a minimal code example that showcases the issue:
[Fact]
public void SampleForServideProviderConfiguration()
{
  var serviceProvider = Substitute.For<IServiceProvider>();
  var scopeSubstitute = Substitute.For<IServiceScope>();
  serviceProvider.CreateScope().Returns(scopeSubstitute);
}
[Fact]
public void SampleForServideProviderConfiguration()
{
  var serviceProvider = Substitute.For<IServiceProvider>();
  var scopeSubstitute = Substitute.For<IServiceScope>();
  serviceProvider.CreateScope().Returns(scopeSubstitute);
}


On the last line I get the error:

An exception of type 'System.InvalidOperationException' occurred in Microsoft.Extensions.DependencyInjection.Abstractions.dll but was not handled in user code: 'No service for type 'Microsoft.Extensions.DependencyInjection.IServiceScopeFactory' has been registered.'
An exception of type 'System.InvalidOperationException' occurred in Microsoft.Extensions.DependencyInjection.Abstractions.dll but was not handled in user code: 'No service for type 'Microsoft.Extensions.DependencyInjection.IServiceScopeFactory' has been registered.'
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements
Next page

Similar Threads

❔ Mocking with EntityFrameworkCore
C#CC# / help
4y ago
ServiceProvider not providing registered service [Answered]
C#CC# / help
4y ago
✅ Mocking DB operations
C#CC# / help
13mo ago
TDD: Mocking services
C#CC# / help
2y ago