依赖注入 IApplicationEnvironment 错误

Dependency Injection IApplicationEnvironment Error

一整天我都在努力让它工作。

我正在通过这段代码进行依赖注入:

public Startup(IApplicationEnviroment appEnv)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(appEnv.ApplicationBasePath)
        .AddJsonFile("config.json")
        .AddEnvironmentVariables();

    Configuration = builder.Build();
}

每次执行这段代码时,我都会收到以下错误:

我真的很生气,因为我无法让它工作而且我对此一无所知。我对 Asp.Net 和 C# 比较陌生,但这就是教程告诉我要做的。大家知道我的代码有什么问题吗?


也许这有帮助。

#if DEBUG
        services.AddScoped<IMailService, DebugMailService>();
#else
        services.AddScoped<IMailService, RealMailService>();
#endif

我的界面:

public interface IMailService
{
    bool SendMail(string to, string from, string subject, string body);
}

我的 DebugMailService

public class DebugMailService : IMailService
{
    public bool SendMail(string to, string from, string subject, string body)
    {
        Debug.WriteLine($"Sending mail: To: {to}, Subject: {subject}");
        return true;
    }
}

有两种可能:

  1. 您在 project.json 中的 json 架构指向错误的位置。我的是 http://json.schemastore.org/project
  2. 您的智能感知可能有问题。通常的 visual studio 重启在大多数情况下都有效,但如果没有,Whosebug 有很多响应来解决这个问题。随便搜一下。

正如您在下面看到的,智能感知工作正常并找到 IApplicationEnvironment,它存在于 Microsoft.Extensions.PlatformAbstractions

然而,幸运的是在 RC1 中,它不再需要包含 Configuration() 上的 ApplicationBasePath,它存在于 IApplicationEnvironment 中。这意味着它可以根据您的情况将 IApplicationEnvironment 注入 Startup 。我的消息来源:here and here.

所以你可以像这样改变你的启动方法:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .AddEnvironmentVariables();

    Configuration = builder.Build().ReloadOnChanged("appsettings.json");
}

最后,确保你没有任何版本不匹配,如果你在同一个解决方案中包含 beta8rc1-final 包肯定会导致问题。既然你说你是 asp.net 的新手,也是 config.json 的新手,告诉我你可能会混淆 beta 版本和 RC asp.net 核心版本。尽管您可以随意命名,但默认命名已更改为 appsettings.json。因此,再次确保 project.json 文件中的包版本是同一版本。

希望对您有所帮助。