.net 在program.cs管道中注入和使用服务[重复]

4c8rllxm  于 2023-03-24  发布在  .NET
关注(0)|答案(1)|浏览(190)

此问题在此处已有答案

How can I use dbInitializer.Initialize() in .NET 6.0;(1个答案)
How to access DbContext in .NET 6 minimal API Program.cs(1个答案)
4天前关闭。
我有一个服务,我需要注入和项目管道内部使用

//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();

我将在注入此服务(或任何其他服务)时更新以下问题
problem image

e0uiprwp

e0uiprwp1#

为了需要一个有作用域的服务,你需要启动一个作用域,它将在其中生存: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();
}

相关问题