Access Registed Scoped Services and Transient Services using GetService()

28 views Asked by At

Can find the reason why can use Transient Services but Scoped Services

// in programe.cs

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<IConfigurateServices, ConfigurateServices>();
var app = builder.Build();
var test2 = app.Services.GetService<IConfigurateServices>();

with this approarch, it work well (Singleton Also), but when i want to change it scoped Services i get error "Cannot resolve scoped service 'ConfigurationProject.Services.IConfigurateServices' from root".

builder.Services.AddScoped<IConfigurateServices, ConfigurateServices>();

i also check some issue and got solution but i don't know exacty why? is Transient Services created when app start ?

1

There are 1 answers

0
Unseen On

You need to create scope before calling the Scoped service.

public static void DoSomething(WebApplication app)
{
    using IServiceScope? scope = app.Services.CreateScope();
    IConfigurateServices configService = scope.ServiceProvider.GetRequiredService<IConfigurateServices>();
}