0

I was resolving service using like this ServiceProvider.GetService<T>(). But then i found that Resolving Scoped Serivices was getting runtime error during calling the method ServiceProvider.GetService<T>() Saying service not found in root provider. Then i found to resolve creating scope like this,

using (var scope = _serviceProvider.CreateScope())
{
   return scope.ServiceProvider.GetService<T>();
}

I want to create a generic function. But the problem is i don't know when to use service provider scope and when not to use service provider as i don't know the service lifetime type(Scoped/Singleton). How can i create this generic function that will resolve the service without knowing the lifetime or resolving the lifetime issue?

Shakibuz_Zaman
  • 260
  • 1
  • 14

1 Answers1

0

You should not be doing this unless there is a reason for not injecting the services as is meant to. You can take a look here (https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1)

Also, if you are building the service provider before the ConfigureServices(..) ends could result in very subtle bugs very hard to track. Here is more in-depth information about that What are the costs and possible side effects of calling BuildServiceProvider() in ConfigureServices()

Being said all these things, you should define the lifetime of the service in the ConfigureService(..) method on the Startup.cs with something like this

services.AddSingleton<ISingletonService, SingletonService>();
services.AddScoped<IScopedService, ScopedService>();

And when you call this logic

using (var scope = _serviceProvider.CreateScope())
{
   return scope.ServiceProvider.GetService<T>();
}

The ServiceProvider itself handles the service lifetime with the code on the ConfigureServices.

Hope it helps you!