Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/269.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果不使用ASP.NET内核,如何在C#中使用配置?_C# - Fatal编程技术网

如果不使用ASP.NET内核,如何在C#中使用配置?

如果不使用ASP.NET内核,如何在C#中使用配置?,c#,C#,我正在使用.NETCore3.1 Microsoft提供了有关如何使用ASP.NET配置的信息。但是,我找不到任何关于如何在不使用ASP.NET的.NET核心应用程序中使用配置的指南 如何从C#console应用程序访问配置文件?我们有自己的配置子系统,可以搜索一组配置文件,并可以使用注册表重定向到特定配置。没有什么能阻止您基本上编写自己的配置子系统-第一个版本需要4个小时的工作。两者之间没有太大区别 现在,我假设您不只是想控制台。写出这些值,但最终您会希望在一些真实代码中访问它们……下面使用“

我正在使用.NETCore3.1

Microsoft提供了有关如何使用ASP.NET配置的信息。但是,我找不到任何关于如何在不使用ASP.NET的.NET核心应用程序中使用配置的指南


如何从C#console应用程序访问配置文件?

我们有自己的配置子系统,可以搜索一组配置文件,并可以使用注册表重定向到特定配置。没有什么能阻止您基本上编写自己的配置子系统-第一个版本需要4个小时的工作。

两者之间没有太大区别

现在,我假设您不只是想控制台。写出这些值,但最终您会希望在一些真实代码中访问它们……下面使用“UserController”作为需要访问配置值的代码

好的,dotnet core最重要的一点是将配置(通常是POCO类)(有关更多选项,请参阅本答案后面的IOptions)注入到需要配置的代码中。您不会像在dotnet framework中那样“从app.config或web.config获取值”。 请重新阅读,并用它来改变您对dotnet框架的想法。这一点我怎么强调都不过分。您需要配置值的“真实代码”不应该出去读取文件……您应该将poco(或
IOptions
)注入到您的类中

这是我在dotnet核心控制台应用程序中进行的典型设置

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

public static class Program
{
    public static int Main(string[] args)
    {
        try
        {
            /* look at the Project-Properties/Debug(Tab) for this environment variable */
            string environmentName = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
            Console.WriteLine(string.Format("DOTNET_ENVIRONMENT='{0}'", environmentName));
            Console.WriteLine(string.Empty);

            IConfigurationBuilder builder = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json")
                    .AddJsonFile($"appsettings.{environmentName}.json", true, true)
                    .AddEnvironmentVariables();
            /* pay attention to the "true, true" arguments above, they reflect optional: true, reloadOnChange: true ..  "optional" being the important one here */


            IConfigurationRoot myconfig = builder.Build();

            IServiceProvider servicesProvider = BuildDi(myconfig );
            using (servicesProvider as IDisposable)
            {
                /* now do something with your properly composed IoC container */

                /* maybe something like this...*/
                IUserController uc = servicesProvider.GetRequiredService<IUserController>();

                 /* UserController will have the email-config injected into it, because you did the IoC container setup correctly in "BuildDi" method .. later in this answer */

                Console.WriteLine("Press ANY key to exit");
                Console.ReadLine();
            }
什么事

有一个神奇的环境变量来驱动事物

我发现.net核心控制台应用程序有几个不同名称的地方之一是:

因此,对于asp.net核心应用程序,我设置

ASPNETCORE_ENVIRONMENT 
对于dotnet核心控制台应用程序,我设置

DOTNET_ENVIRONMENT
============

public class EmailConfig {
    public string Username { get; set;}  
    public string Password { get; set;} 
}
public class UserController : IUserController
{
    private readonly EmailConfig _emailConfig;

    public UserController(EmailConfig emailConfig)
    {
        _emailConfig = emailConfig;

        //_emailConfig.Username
        //_emailConfig.Password
    }
}
    private static IServiceProvider BuildDi(IConfiguration myconfig)
    {


        ////setup our DI
        IServiceCollection servColl = new ServiceCollection()
            .AddLogging();  /* do any other stuff here that is extension method */


        EmailConfig emailConfig = new EmailConfig();
        myconfig.GetSection("Email").Bind(emailConfig);
        /* you may want to check for null here on emailConfig */

        //Create singleton from instance..and push to the IoC container
        servColl.AddSingleton<EmailConfig>(emailConfig);

         /* not shown here.. but you'll need to add IUserController,UserController as well */

        ServiceProvider servProv = servColl.BuildServiceProvider();

        return servProv;
    }
因此,对于上述内容,您必须至少有一个“appsettings.json”文件

但是您可以选择拥有这些文件

appsettings.Development.json
appsettings.Staging.json
appsettings.Production.json
你可以在这里阅读更多关于这方面的内容:

现在,如何将.json文件中的那些值放入需要它们的代码中

在dotnetcore中,配置poco通常被注入到类中

以上是一个很好的例子

=======================

public class EmailConfig {
    public string Username { get; set;}  
    public string Password { get; set;} 
}
public class UserController : IUserController
{
    private readonly EmailConfig _emailConfig;

    public UserController(EmailConfig emailConfig)
    {
        _emailConfig = emailConfig;

        //_emailConfig.Username
        //_emailConfig.Password
    }
}
    private static IServiceProvider BuildDi(IConfiguration myconfig)
    {


        ////setup our DI
        IServiceCollection servColl = new ServiceCollection()
            .AddLogging();  /* do any other stuff here that is extension method */


        EmailConfig emailConfig = new EmailConfig();
        myconfig.GetSection("Email").Bind(emailConfig);
        /* you may want to check for null here on emailConfig */

        //Create singleton from instance..and push to the IoC container
        servColl.AddSingleton<EmailConfig>(emailConfig);

         /* not shown here.. but you'll need to add IUserController,UserController as well */

        ServiceProvider servProv = servColl.BuildServiceProvider();

        return servProv;
    }
=======================

public class EmailConfig {
    public string Username { get; set;}  
    public string Password { get; set;} 
}
public class UserController : IUserController
{
    private readonly EmailConfig _emailConfig;

    public UserController(EmailConfig emailConfig)
    {
        _emailConfig = emailConfig;

        //_emailConfig.Username
        //_emailConfig.Password
    }
}
    private static IServiceProvider BuildDi(IConfiguration myconfig)
    {


        ////setup our DI
        IServiceCollection servColl = new ServiceCollection()
            .AddLogging();  /* do any other stuff here that is extension method */


        EmailConfig emailConfig = new EmailConfig();
        myconfig.GetSection("Email").Bind(emailConfig);
        /* you may want to check for null here on emailConfig */

        //Create singleton from instance..and push to the IoC container
        servColl.AddSingleton<EmailConfig>(emailConfig);

         /* not shown here.. but you'll need to add IUserController,UserController as well */

        ServiceProvider servProv = servColl.BuildServiceProvider();

        return servProv;
    }
.json将附加额外的自定义配置部分/区域……下面的示例显示了默认的.json文件……但添加了“Email”部分

"ConnectionStrings": {
  "DefaultConnection": ""
},
"Logging": {
  "IncludeScopes": false,
  "LogLevel": {
    "Default": "Warning"
  }
},
"Email": {
  "Username": "peanut",
  "Password": "butter"
}
=======================

public class EmailConfig {
    public string Username { get; set;}  
    public string Password { get; set;} 
}
public class UserController : IUserController
{
    private readonly EmailConfig _emailConfig;

    public UserController(EmailConfig emailConfig)
    {
        _emailConfig = emailConfig;

        //_emailConfig.Username
        //_emailConfig.Password
    }
}
    private static IServiceProvider BuildDi(IConfiguration myconfig)
    {


        ////setup our DI
        IServiceCollection servColl = new ServiceCollection()
            .AddLogging();  /* do any other stuff here that is extension method */


        EmailConfig emailConfig = new EmailConfig();
        myconfig.GetSection("Email").Bind(emailConfig);
        /* you may want to check for null here on emailConfig */

        //Create singleton from instance..and push to the IoC container
        servColl.AddSingleton<EmailConfig>(emailConfig);

         /* not shown here.. but you'll need to add IUserController,UserController as well */

        ServiceProvider servProv = servColl.BuildServiceProvider();

        return servProv;
    }
=======================

public class EmailConfig {
    public string Username { get; set;}  
    public string Password { get; set;} 
}
public class UserController : IUserController
{
    private readonly EmailConfig _emailConfig;

    public UserController(EmailConfig emailConfig)
    {
        _emailConfig = emailConfig;

        //_emailConfig.Username
        //_emailConfig.Password
    }
}
    private static IServiceProvider BuildDi(IConfiguration myconfig)
    {


        ////setup our DI
        IServiceCollection servColl = new ServiceCollection()
            .AddLogging();  /* do any other stuff here that is extension method */


        EmailConfig emailConfig = new EmailConfig();
        myconfig.GetSection("Email").Bind(emailConfig);
        /* you may want to check for null here on emailConfig */

        //Create singleton from instance..and push to the IoC container
        servColl.AddSingleton<EmailConfig>(emailConfig);

         /* not shown here.. but you'll need to add IUserController,UserController as well */

        ServiceProvider servProv = servColl.BuildServiceProvider();

        return servProv;
    }
和德国csproj零件

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.*" />
    <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="3.1.*" />

  </ItemGroup>

您可以拥有一个
appsettings.json
文件。 然后您可以使用一个类来表示此文件,如:

public class Settings
{
    public string ConnectionString { get; set; }
}
然后,在
main
方法中,您可以读取Json文件,并使用
System.Text.Json
将其反序列化到所需的类中,如:

using (var fs = File.OpenRead(fileName))
{
    var settings = JsonSerializer.Deserialize<Settings>(fs);
    // set this in a accessible variable
}
使用(var fs=File.OpenRead(文件名))
{
var settings=JsonSerializer.Deserialize(fs);
//在可访问的变量中设置此值
}

配置功能没有内置到.NET核心(显然)。您需要使用Nuget和一些启动配置注入它。基本上,您需要注册您的配置。这里是如何

安装NuGet软件包:

Install-Package Microsoft.Extensions.Configuration
Install-Package Microsoft.Extensions.Configuration.Json
Install-Package Microsoft.Extensions.Configuration.CommandLine
Install-Package Microsoft.Extensions.Configuration.EnvironmentVariables 
appsettings.json
文件添加到根级别的项目中。您需要像这样注册它:

static async Task Main(string[] args)
{

  IConfiguration Configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddEnvironmentVariables()
    .AddCommandLine(args)
    .Build();
}
现在,您的提供商已在console应用程序中注册,您可以这样引用您的配置:

var section = Configuration.GetSection("MySectionOfSettings");
var configValue = Configuration.GetValue("MySetting");

上面AussieJoe给出的最佳答案是好的,但如果不这样做,它将不起作用:

  • 添加Nuget软件包Microsoft.Extensions.Configuration.Binder

  • 改变 var configValue=Configuration.GetValue(“MySetting”); 到 var configValue=Configuration.GetValue(“MySetting”)

  • 新建ConfigurationBuilder()
    上,也添加此选项
    .SetBasePath(Directory.GetCurrentDirectory())

  • 换言之:
    IConfiguration Configuration=new ConfigurationBuilder().AddJsonFile(“appsettings.json”,可选:true,reloadOnChange:true)。AddEnvironmentVariables().AddCommandLine(args)。SetBasePath(Directory.GetCurrentDirectory())//添加此行。Build()

    您对使用
    WorkerService
    模板有何看法?它可以作为控制台运行,也可以作为服务/守护程序安装。它的好处在于它附带了
    依赖项注入
    配置
    服务box@WBuckWorkerService看起来不错!我会记在心里的。所以只是一个友好的评论。DotnetCore已经在中使用了这一功能。这就是迷你们重新发明轮子。对于“如何从json文件创建poco”来说,这是一个很好的答案。但是对于.appsettings来说,这是一个很小的创新。感谢您的全面回答。您使用环境变量来定义环境,但由于我的应用程序不是web应用程序,而是将要分发的应用程序,所以我无法控制最终用户机器上的环境变量,对吗?因此,我需要考虑未定义的环境变量作为生产。您不必使用环境变量的东西。只需删除添加特定的AddJsonFile行。当然还有读取设置的代码。我在回答中没有特别提到“web应用程序”。我写的答案是针对一个控制台应用程序的(因为我和他们一起经历了这场火灾)。我只是想把整个画面中的几个点连起来。