[英]How to read appsettings.json values ASP.NET Core
After I've read this article about dependency injection Here I still do not have a clear understanding on how to read the appsetting in other than a controller classes. 我读过这篇文章大约依赖注入后, 在这里我仍然没有就如何读取其他的appsetting比控制器类清醒的认识。
Lets say for instance I have a helper class with a bunch of static methods that I'm planning to use, I do not create an instance of this class, how do I read setting values to use inside the methods of this class? 可以说,例如,我有一个计划使用一堆静态方法的帮助程序类,没有创建此类的实例,如何读取设置值以在此类方法中使用?
I used to create helper class to read data from appsettings.config in one of my applications: 我曾经创建助手类来从我的一个应用程序中的appsettings.config中读取数据:
public static class ConfigValueProvider
{
private static readonly IConfigurationRoot Configuration;
static ConfigValueProvider()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public static string Get(string name)
{
return Configuration[name];
}
}
However later I reviewed my application to get away from static
methods which depends on application config in order to make my application testable. 但是,后来我查看了我的应用程序,以摆脱依赖于应用程序配置的
static
方法,以使我的应用程序可测试。
You should use services.Configure as below: 您应该使用services.Configure如下:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<JSonAsClass>(Configuration.GetSection("MySectionName"));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
then you can inject JSonAsClass inside any class you want to use it: 那么您可以将JSonAsClass注入要使用的任何类中:
private JSonAsClass jSonAsClass;
public MailService(IOptions<JSonAsClass> jSonAsClass)
{
this.jSonAsClass = jSonAsClass.Value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.