Reputation: 61
While consuming a scoped from singleton I am not getting any error
According to below article, i should get an error as soon as I start my service:
https://dotnetcoretutorials.com/2018/03/20/cannot-consume-scoped-service-from-singleton-a-lesson-in-asp-net-core-di-scopes/
Dependency Registered :
builder.Services.AddScoped<ILogger, AppLogs>();
builder.Services.AddSingleton<ICacheFactory>(x =>
{
string cacheConnectionString = "xyz";
return new CacheFactory(cacheConnectionString, x.GetService<ILogger>());
});
Consumed:
public class Function1
{
private readonly ICacheFactory cacheProvider;
public Function1(ICacheFactory cacheProvider) {
this.cacheProvider = cacheProvider;
}
[FunctionName("Function1")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
var result = await this.cacheProvider.GetResultsAsync<IEnumerable<string>>("abc").ConfigureAwait(false);}
}
When does a scoped injected in a singleton give an issue?
Upvotes: 0
Views: 473
Reputation: 2474
To get an error when using scoped services in singleton instances you must set the ValidateScopes option to true when building the service provider e.g.
var provider = services.BuildServiceProvider(validateScopes: true);
The validation is somewhat expensive so you can change it to only validate when you are developing like this:
var provider = services.BuildServiceProvider(validateScopes: Debugger.IsAttached);
Documentation on BuildServiceProvider
Upvotes: 1