相关疑难解决方法(0)

如何使用IHostingEnvironment

如何在IHostingEnvironment不在构造函数中启动它的情况下使用该 接口?

我的Startup.cs:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();

    if (env.IsDevelopment())
    {
        // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
        builder.AddApplicationInsightsSettings(developerMode: true);
    }
    Configuration = builder.Build();
}
Run Code Online (Sandbox Code Playgroud)

我的课:

public class FileReader
{
    // I don't want to initiate within a constructor

    public string ReadFile(string fileName)
    {
       // this is wrong! how can I use it?
       var …
Run Code Online (Sandbox Code Playgroud)

.net asp.net-core

12
推荐指数
1
解决办法
1万
查看次数

在.NetCore库中使用IHostingEnvironment

我构建了一个应用程序Asp.net core,我创建了一个.Net core class library单元测试,我想IHostingEnvironment在我的库中使用(用于获取文件的物理路径),所以我将它添加到我的Asp.net核心应用程序服务的startup.cs:

 services.AddSingleton<IHostingEnvironment>();
Run Code Online (Sandbox Code Playgroud)

在库中我添加了对我的Asp.net应用程序的引用,并在我的库中的类我写道:

  private IHostingEnvironment _env;
    public Class1(IHostingEnvironment env)
    {
        _env = env;
    }
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,它给了我这个错误:

以下构造函数参数没有匹配的fixture日期:IHostingEnvironment env

问题是什么?我该如何使用它.NetCore library

编辑:我也这样使用:

        IServiceCollection services = new ServiceCollection();
        services.AddSingleton<IHostingEnvironment>();
        IServiceProvider provider = services.BuildServiceProvider();
        IHostingEnvironment service = provider.GetService<IHostingEnvironment>();
        var p = service.WebRootPath; // give this error: Cannot instantiate implementation type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' for service type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment'
Run Code Online (Sandbox Code Playgroud)

但它也不起作用.

asp.net-core

8
推荐指数
2
解决办法
1万
查看次数

标签 统计

asp.net-core ×2

.net ×1