首页 > 解决方案 > appsettings.json 文件不在 .net 核心控制台项目中

问题描述

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

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

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

标签: asp.net-core.net-core

解决方案


非 web 项目可能需要也可能不需要配置。但是,正如您所注意到的,Visual Studio 不会使用appsettings.json. 显然,您可以将其作为 json 文件添加到项目中。一旦拥有它,挑战就是如何利用它。我经常在实体框架实用程序中使用配置对象和依赖注入。

例如,

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运行迁移和基于控制台的实用程序。你没有指定你需要什么样的配置——所以这只是一个例子。但希望您可以根据自己的需要进行调整。


推荐阅读