在 ConfigureServices 中访问 IApplicationEnvironment

Access IApplicationEnvironment in ConfigureServices

在我的 ConfigureServices 方法中,我想读取一个文件(在我的例子中是用于签署令牌的证书,但它可以是设置服务所需的任何文件)。因此我需要从 IApplicationEnvironment.

知道 ApplicationBasePath

目前我通过这样获取 IApplicationEnvironment 服务来解决问题:

public void ConfigureServices(IServiceCollection services)
{
    ...
    string basePath;
    var serviceProvider = services.BuildServiceProvider();
    try
    {
        basePath = serviceProvider.GetRequiredService<IApplicationEnvironment>().ApplicationBasePath;
    }
    finally
    {
        (serviceProvider as IDisposable)?.Dispose();
    }
    ...
}

这种方法可行,但我不确定这是否是正确的方法。所以我的问题是:

  1. 有没有更好的方法来读取 ConfigureServices 中的文件?
  2. ConfigureServices中是否有更好的获取应用程序基本路径的方法?
  3. 如果我的方法是正确的,我是否正确处理了IDisposable

运行时允许在 Startup class 的构造函数中进行依赖注入:

public class Startup
{
    private readonly IApplicationEnvironment _appEnv;

    public Startup(IApplicationEnvironment appEnv)
    {
        _appEnv = appEnv;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        string basePath = _appEnv.ApplicationBasePath;
    }
}

DNX 1.0.0-rc1-15996发布后如何获取IApplicationEnvironment实例

要获取对 IApplicationEnviroment 接口实现者的引用,您可以使用 PlatformServices.Default.Application

以下示例在项目的 Startup.cs 文件的上下文中显示了这一点:

using Microsoft.Extensions.PlatformAbstractions;

namespace MyWebApp
{
    public class Startup
    {       
        private IApplicationEnvironment _appEnv { get; set; }

        public Startup(IHostingEnvironment env)
        {
            // Set up configuration sources.
            var builder = new ConfigurationBuilder()                
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false);

            if (env.IsDevelopment())
            {
                // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
                builder.AddUserSecrets();
            }

            builder.AddEnvironmentVariables();          
            Configuration = builder.Build();

            // obtain IApplicationEnvironment instance
            _appEnv = PlatformServices.Default.Application;

        }
...

下一行显示了如何使用该实例获取应用程序的基本路径:

 string basepath = _appEnv.ApplicationBasePath

参考文献:

  1. Refactoring DNX not to inject into Program constructors #2990
  2. IApplicationEnvironment no longer injected in DNX command

为什么不直接从 PlatformServices.Default.Application.ApplicationBasePath 分配路径?正如名称 Default 所暗示的(不完全是规则,因为 Current 也在这里和那里使用),它是类型 PlatformServices 的静态成员。

更多详情...

除了DefaultApplication类型的ApplicationEnvironment是class暴露的唯一属性。这是合理的,因为 ApplicationEnvironment 只是封装了一些关于 运行 应用程序(或应用程序,无论它们有多少)的信息。同样重要的是,class' 默认的 ctor 是 private。闻起来像 Singleton,嗯?

显然实施者的决定是改变对应用程序环境的看法:它没有任何作用,它是一个共享信息。使用它的唯一方法是上面的方法。

还有更多...

IApplicationEnvironment 又一次神奇地消失了,因为事实证明 ApplicationEnvironment 不是一项预期会针对不同操作系统进行 DI 或重新实现的服务,也许从这一点开始上,ApplicationEnvironment 没有执行任何操作。 非常好!