简体   繁体   English

如何在 asp.net 内核 6 中注入 IConfiguration

[英]How to inject IConfiguration in asp.net core 6

There is no Startup.cs in the web/api application any more. web/api 应用程序中不再有 Startup.cs。

We used to be able to inject IConfiguration into that Startup class.我们曾经能够将IConfiguration注入到Startup class 中。

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration
    }
    ...
}

Now that those add service and configuration code is moved into Program.cs , what is the correct way to access configuration from there?现在那些添加服务和配置代码已移至Program.cs ,从那里访问配置的正确方法是什么?

You could add the IConfiguration instance to the service collection as a singleton object in ConfigureServices :您可以在ConfigureServices中将IConfiguration实例作为 singleton object 添加到服务集合中:

 public void ConfigureServices(IServiceCollection service){ services.AddSingleton<IConfiguration>(Configuration);  // ...} }

This allows you to inject IConfiguration in any controllers or classes:这允许您在任何控制器或类中注入IConfiguration

public class UserController{public UserController(IConfiguration configuration)

  // Use IConfiguration instance here}

As far as I can tell, they replaced it with a concrete instance of ConfigurationManager class which is a property of the WebApplicationBuilder.据我所知,他们将其替换为 ConfigurationManager class 的具体实例,这是 WebApplicationBuilder 的属性。

In your Program.cs class there is a line of code:在您的 Program.cs class 中有一行代码:

 var builder = WebApplication.CreateBuilder(args);

You can then access the configuration from this builder instance:然后,您可以从此构建器实例访问配置:

 builder.Configuration.GetConnectionString("DefaultConnection");

I know this does not answer your "how to inject IConfiguration" question but I'm guessing you just want to be able to access your configuration settings.我知道这并不能回答您的“如何注入 IConfiguration”问题,但我猜您只是希望能够访问您的配置设置。 If not you can downvote my answer.如果不是,您可以否决我的回答。

The IConfiguration can be accessed in the WebApplicationBuilder . IConfiguration可以在WebApplicationBuilder中访问。

在此处输入图像描述

So no need to inject IConfiguration any more, it is now a property in the builder in Program.cs .所以不再需要注入IConfiguration ,它现在是Program.csbuilder中的一个属性。 在此处输入图像描述

var builder = WebApplication.CreateBuilder(args);
var config = builder.Configuration;

builder.Services.AddInfrastructureServices(config);
builder.Services.AddPersistenceServices(config);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM