【问题标题】:IConfiguration in Startup.csStartup.cs 中的 IConfiguration
【发布时间】:2021-03-16 03:59:46
【问题描述】:

IConfiguration会自动添加到Startup.ca

    public Startup(IConfiguration configuration)
    {
        conf = configuration;
    }

类似地,我们可以通过依赖注入将它添加到控制器中。现在这是一个接口,但我们仍然可以像使用类一样使用它的方法(例如conf.GetSection)。 IConfiguration 的继承类在哪里以及如何设置,我们可以使用其返回值的方法?

【问题讨论】:

  • 如果我没记错的话,我想你想要 appSettings.json
  • 我知道cong.GetSection 做了什么。我只是不明白接口如何获得该值。当我们有一个用于依赖注入的接口时,这里使用的是什么类(连接到接口)?
  • 查看文档并查看从该接口派生的类docs.microsoft.com/en-us/dotnet/api/…
  • 我在问这个实现发生在幕后的什么地方
  • 这是框架的工作,通常没有人知道,直到他阅读了源代码(在 Github 上公开)。对于大多数开发人员(甚至是专业人士)和大多数情况下,我们通常不需要关心这一点。所以你想知道这件事有点奇怪。相反,我们还有很多其他事情需要关注。当然,当你有充分的理由必须知道这一点时,这是有道理的。

标签: asp.net-core .net-core asp.net-core-mvc


【解决方案1】:

作为King King的cmets,IConfiguration是在program.cs中调用Build方法时默认注入的服务。您会发现它调用了BuildCommonServices method,它将注入 IConfiguration 服务。 IConfiguration 服务将使用 IConfigurationBuilder 的构建方法创建。如果你想知道 DI 在 asp.net core 中是如何工作的,我建议你可以参考这个article

WebHostBuilder 类的某些部分。

public IWebHost Build()
    {
      if (this._webHostBuilt)
        throw new InvalidOperationException(Resources.WebHostBuilder_SingleInstance);
      this._webHostBuilt = true;
      AggregateException hostingStartupErrors;
      IServiceCollection serviceCollection1 = this.BuildCommonServices(out hostingStartupErrors);
      IServiceCollection serviceCollection2 = serviceCollection1.Clone();
      IServiceProvider providerFromFactory = GetProviderFromFactory(serviceCollection1);
      .....

    WebHost webHost = new WebHost(serviceCollection2, providerFromFactory, this._options, this._config, hostingStartupErrors);
      try
      {
        webHost.Initialize();
        return (IWebHost) webHost;
      }
      catch
      {
        webHost.Dispose();
        throw;
      }

    IServiceProvider GetProviderFromFactory(IServiceCollection collection)
      {
        ServiceProvider serviceProvider = collection.BuildServiceProvider();
        IServiceProviderFactory<IServiceCollection> service = ((IServiceProvider) serviceProvider).GetService<IServiceProviderFactory<IServiceCollection>>();
        if (service == null)
          return (IServiceProvider) serviceProvider;
        using (serviceProvider)
          return service.CreateServiceProvider(service.CreateBuilder(collection));
      }
    }

【讨论】:

    猜你喜欢
    • 2019-07-27
    • 2022-11-29
    • 2021-07-06
    • 2020-09-14
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 2021-11-01
    • 2015-10-18
    相关资源
    最近更新 更多