依赖注入IApplicationEnvironment错误

Tom*_*adi 19 c# asp.net asp.net-mvc dependency-injection config

一整天我都试图让这个工作.

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

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

    Configuration = builder.Build();
}
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

我真的很生气,因为我不能让它工作,我不知道它.我对Asp.Net和C#比较新,但这就是教程说我要做的事情.大家都知道我的代码问题是什么吗?


也许这个问题.

#if DEBUG
        services.AddScoped<IMailService, DebugMailService>();
#else
        services.AddScoped<IMailService, RealMailService>();
#endif
Run Code Online (Sandbox Code Playgroud)

我的界面:

public interface IMailService
{
    bool SendMail(string to, string from, string subject, string body);
}
Run Code Online (Sandbox Code Playgroud)

我的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*eer 5

有两种可能性:

  1. project.json中的json模式指向错误的位置.我的是http://json.schemastore.org/project
  2. 你的intellisense可能会给出问题.通常的visual studio重启很多次,但如果没有,stackoverflow会有很多响应来解决这个问题.只是搜索它.

正如你在下面看到的那样,intellisense工作得很好并且找到了IApplicationEnvironment,它存在于Microsoft.Extensions.PlatformAbstractions.

IApplicationEnvironment

然而,幸运的是在RC1,它不再需要包括ApplicationBasePathConfiguration(),它存在于IApplicationEnvironment.这意味着其可选注入IApplicationEnvironmentStartup你的情况.我的消息来源:这里这里.

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

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

    Configuration = builder.Build().ReloadOnChanged("appsettings.json");
}
Run Code Online (Sandbox Code Playgroud)

最后,确保你不要有任何版本不匹配,这肯定会导致问题,如果您有beta8rc1-final在同一个解决方案包.既然你说你是asp.net的新用户,并且使用了config.json,告诉我你可能会混淆使用RC asp.net核心版本的beta版本.即使您可以将其命名为任何名称,默认命名也会更改为appsettings.json.因此,请确保project.json文件中的软件包版本位于同一版本中.

我希望这有帮助.