"Cannot resolve scoped service" in Development environment
See original GitHub issueHi!
Environment: Windows 10 Visual studio 2019 Version 16.10.3 Asp.NET core 3.1
I have simple asp.net core app which launched with Kestrel. I am experimenting with HttpClientFactory and have caught an interesting behaviour. I have 2 services. First:
public interface IService1
{
void Inc();
string ToString();
}
public class Service1: IService1
{
public int _count = 0;
public Service1(HttpClient client, IService2 s2)
{
}
public void Inc()
{
_count++;
}
public override string ToString()
{
return $"{nameof(Service1)}, count {_count}";
}
}
Second:
public interface IService2
{
void Inc();
string ToString();
}
public class Service2 : IService2
{
public int _count = 0;
public Service2()
{
}
public void Inc()
{
_count++;
}
public override string ToString()
{
return $"{nameof(Service2)}, count {_count}";
}
}
I have registered them inside ConfigureServices:
services.AddScoped<IService2, Service2>();
services.AddHttpClient<IService1, Service1>();
And in Configure(…) method I am tryin call my Service1:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var s1 = app.ApplicationServices.GetRequiredService<IService1>();
s1.Inc();
s1 = app.ApplicationServices.GetRequiredService<IService1>();
s1.Inc();
Console.WriteLine(s1);
...
}
If I start this code in Visual Studio (doesn’t matter in Debug or Release mode), exception is throwing: System.InvalidOperationException: ‘Cannot resolve scoped service ‘WebApplication1.IService2’ from root provider.’
If I start application with double click on exe file, application successfully starts. Difference was in “ASPNETCORE_ENVIRONMENT” variable. As I removed it from Visual Studio debug settings, the app was started successfully in Visual Studio as well.
Is this behaviour a bug or a feature?
Thank in advance!
Issue Analytics
- State:
- Created 2 years ago
- Comments:7 (2 by maintainers)
@Vake93 is correct, it’s the performance impact.
Not 100% sure about this, but I think there is a performance impact when you validate the scopes when dependencies are resolved. So that is probably why it is skipped by default in the production environment. Also, since you would have tested the application in development before pushing it to production, you would catch the issue.