asp.net-core - appsettings.json 文件不在 .net 核心控制台项目中

标签 asp.net-core .net-core

我了解到 .net core 已将 app.config 文件替换为 appsetting.json。然而,这个文件似乎只是为 ASP.net 项目添加的。事实上,它甚至在添加项目列表中都不可用。 我找到了 this发布需要添加的包列表:

  1. Microsoft.Extensions.Configuration
  2. Microsoft.Extensions.Configuration.FileExtensions
  3. Microsoft.Extensions.Configuration.Json

我添加了所有这些,它确实为我提供了添加 json 配置文件的选项,但仍然没有添加仅在 ASP.Net Core 下可用的 App Settings File。 我试图理解为什么非 Web 项目不需要配置以及配置 .net 核心控制台应用程序的推荐方法是什么。 提前致谢。

最佳答案

非网络项目可能可能需要配置。但是,正如您所注意到的,Visual Studio 不会使用 appsettings.json 构建控制台项目。显然,您可以将它作为 json 文件添加到项目中。一旦拥有它,挑战就是如何利用它。我经常在 Entity Framework 实用程序中使用配置对象和依赖项注入(inject)。

例如,

public static class Program
{
    private static IConfigurationRoot Configuration { get; set; }

    public static void Main()
    {
        IConfigurationBuilder builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .AddEnvironmentVariables();
        Configuration = builder.Build();

        IServiceCollection services = new ServiceCollection();
        services.AddDbContext<MyDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddScoped<IMyService, MyService>();
        IServiceProvider provider = services.BuildServiceProvider();

        IMyService myService = provider.GetService<IMyService>();
        myService.SomeMethod();
    }

    public class TemporaryDbContextFactory : IDesignTimeDbContextFactory<MyDbContext>
    {
        public MyDbContext CreateDbContext(string[] args)
        {
            IConfigurationBuilder configBuilder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddEnvironmentVariables();
            IConfigurationRoot configuration = configBuilder.Build();
            DbContextOptionsBuilder<MyDbContext> builder = new DbContextOptionsBuilder<MyDbContext>();
            builder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
            return new MyDbContext(builder.Options);
        }
    }
}

这允许我针对 DbContext 运行迁移基于控制台的实用程序。你没有指定你需要什么样的配置 - 所以这只是一个例子。但希望您可以根据自己的需要进行调整。

关于asp.net-core - appsettings.json 文件不在 .net 核心控制台项目中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57243885/

相关文章:

c# - second level如何加载couple相关数据?

c# - 在 .NET Core 2.1 控制台应用程序中配置用户 secret

c# - 如何从 SSL key 文件创建 RsaSecurityKey 实例

c# - 在 Powershell 中运行时与在 Visual Studio 中运行时的 HttpClient 并发行为不同

c# - 如何在服务层获取用户

c# - 未传递 IActionResult 参数

asp.net-mvc - 如何在 ASP.NET Core 的 Razor Pages 中设置全局变量?

angularjs - 在 VS2015 Update 2 中使用 npm 安装 Angular 2 包时出现问题

docker - Raspberry 4b上Docker镜像内的.NET Core

c# - Asp.Net Core 中的本地化