gpt4 book ai didi

c# - 在 ConfigureServices 中访问 IApplicationEnvironment

转载 作者:太空狗 更新时间:2023-10-29 22:15:56 26 4
gpt4 key购买 nike

在我的 ConfigureServices 方法中,我想读取一个文件(在我的例子中是一个用于签署 token 的证书,但它可以是设置服务所需的任何文件)。因此,我需要知道 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 类的构造函数中进行依赖注入(inject):

public class Startup
{
private readonly IApplicationEnvironment _appEnv;

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

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

关于c# - 在 ConfigureServices 中访问 IApplicationEnvironment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31066068/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com