Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

inject and use services in program.cs pipeline

I have a service that I need to inject and use inside the project pipeline

//Register Service
builder.Services.AddScoped<IDbInitializer, DbInitializer>();

//Build App and Inject Service
var app = builder.Build();
var dbInitializer = app.Services.GetService<IDbInitializer>();

//Use 
dbInitializer.Initialize();

I will update the following problem when injecting this service (or any other service)

problem image

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In order to require a scoped service, you need to initiate a scope inside which it will live: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-7.0#resolve-a-service-at-app-start-up

//Register Service
builder.Services.AddScoped<IDbInitializer, DbInitializer>();

//Build App and Inject Service
var app = builder.Build();
using (IServiceScope scope = app.Services.CreateScope())
{
    IDbInitializer dbInitializer = scope.ServiceProvider.GetRequiredService<IDbInitializer>();

    //Use 
    dbInitializer.Initialize();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading