.net-core – 用于.NET Core控制台应用程序的ASP.NET Core配置

前端之家收集整理的这篇文章主要介绍了.net-core – 用于.NET Core控制台应用程序的ASP.NET Core配置前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
ASP.NET Core支持新配置系统,如下所示:
https://docs.asp.net/en/latest/fundamentals/configuration.html

.NET Core控制台应用程序中还支持这种模式吗?

如果不是以前的app.config和ConfigurationManager模型的替代品?

解决方法

您可以使用此代码段.它包括配置和DI.
public class Program
{
    public static ILoggerFactory LoggerFactory;
    public static IConfigurationRoot Configuration;

    public static void Main(string[] args)
    {
        Console.OutputEncoding = Encoding.UTF8;

        string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

        if (String.IsNullOrWhiteSpace(environment))
            throw new ArgumentNullException("Environment not found in ASPNETCORE_ENVIRONMENT");

        Console.WriteLine("Environment: {0}",environment);

        var services = new ServiceCollection();

        // Set up configuration sources.
        var builder = new ConfigurationBuilder()
            .SetBasePath(Path.Combine(AppContext.BaseDirectory))
            .AddJsonFile("appsettings.json",optional: true);
        if (environment == "Development")
        {

            builder
                .AddJsonFile(
                    Path.Combine(AppContext.BaseDirectory,string.Format("..{0}..{0}..{0}",Path.DirectorySeparatorChar),$"appsettings.{environment}.json"),optional: true
                );
        }
        else
        {
            builder
                .AddJsonFile($"appsettings.{environment}.json",optional: false);
        }

        Configuration = builder.Build();

        LoggerFactory = new LoggerFactory()
            .AddConsole(Configuration.GetSection("Logging"))
            .AddDebug();

        services
            .AddEntityFrameworkNpgsql()
            .AddDbContext<FmDataContext>(o => o.UseNpgsql(connectionString),ServiceLifetime.Transient);

        services.AddTransient<IPackageFileService,PackageFileServiceImpl>();

        var serviceProvider = services.BuildServiceProvider();

        var packageFileService = serviceProvider.GetrequiredService<IPackageFileService>();

        ............
    }
}

哦,不要忘了在project.json中添加

{
  "version": "1.0.0-*","buildOptions": {
    "emitEntryPoint": true,"copyToOutput": {
      "includeFiles": [
        "appsettings.json","appsettings.Integration.json","appsettings.Production.json","appsettings.Staging.json"
      ]
    }
  },"publishOptions": {
    "copyToOutput": [
      "appsettings.json","appsettings.Staging.json"
    ]
  },...
}

猜你在找的.NET Core相关文章