如何将自定义 JSON 文件添加到 IConfiguration 中? [英] How can I add a custom JSON file into IConfiguration?

查看:67
本文介绍了如何将自定义 JSON 文件添加到 IConfiguration 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 asp.net + Autofac.

I'm using asp.net + Autofac.

我正在尝试加载自定义 JSON 配置文件,并基于该文件创建/实例化 IConfiguration 实例,或者至少将我的文件包含在默认情况下 IConfiguration asp.net 构建的任何内容中.

I'm trying to load a custom JSON configuration file, and either create/instance an IConfiguration instance based on that, or at least include my file into whatever IConfiguration asp.net builds by default.

我的问题是 asp.net 似乎覆盖了 IConfiguration 的依赖项注册.

My problem is that asp.net seems to override the dependency registration for IConfiguration.

我似乎无法注册自己的 IConfiguration 对象 - DI 容器将始终将此解析为某个似乎由 asp.net 库本身生成的实例.

I can't seem to register my own IConfiguration object - the DI container will always resolve this to some instance that seems to have been generated by the asp.net library itself.

而且我不确定如何让 asp.net 至少额外加载我的自定义配置文件 - 即如果有任何方法可以获取它使用的 ConfigurationBuilder,并在它之前添加我自己的文件构建 IConfiguration 对象.

And I'm not sure how I can get asp.net to at least load my custom config file additionally - i.e. if there is any way to get a hold of the ConfigurationBuilder it uses, and add my own file before it is building the IConfiguration object.

我尝试了以下方法:

public class Startup
{
    public IConfigurationRoot Configuration { get; }

    public Startup(IHostingEnvironment env)
    {
        this.Configuration = new ConfigurationBuilder()
            .SetBasePath(path)
            .AddJsonFile("somefile.json")
            .Build();
    }

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services
          .AddMvc()
          .AddControllersAsServices();

         var builder = new ContainerBuilder();
         builder.Register(x => this.Configuration).As<IConfiguration>();
         builder.Populate(services);

         var container = builder.Build();

         // This will return another IConfiguration instance then the one I registered; 
         // namely One that contains 1 provider, a MemoryConfigurationProvider
         var xxx = container.Resolve<IConfiguration>();

         return new AutofacServiceProvider(container);
    }
}

如何让 asp.net 加载我的自定义 JSON 配置文件?

How can I get asp.net to load my custom JSON config file as well?

推荐答案

您可以使用 选项 模式:

在 ASP.NET Core 2 上,在 Program.cs

On ASP.NET Core 2, register the config file on Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)

             // custom config file
            .AddJsonFile("myappconfig.json", optional: false, reloadOnChange: false)
            .Build();

        BuildWebHost(args, configuration).Run();
    }

    public static IWebHost BuildWebHost(string[] args, IConfiguration config) =>
        WebHost.CreateDefaultBuilder(args)
            .UseConfiguration(config)
            .UseStartup<Startup>()
            .Build();
}

创建一个与您的配置文件匹配的类:

Create a class that matches with your config file:

public class MyAppConfig
{
    public string SomeConfig { get; set; }

    public int NumberConfig { get; set; }
}

ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.Configure<MyAppConfig>(Configuration);
}

然后,只需在您的控制器中访问它:

Then, just access it in your Controller:

[Route("api/[controller]")]
public class ValuesController : Controller
{
    private readonly MyAppConfig _appConfig;

    public ValuesController(IOptions<MyAppConfig> optionsAccessor)
    {
        if (optionsAccessor == null) throw new ArgumentNullException(nameof(optionsAccessor));
        _appConfig = optionsAccessor.Value;
    }

    // GET api/values/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return _appConfig.SomeConfig;
    }
}

如果您还没有使用 ASP.NET Core 2,则过程几乎相同.您只需要在 Startup.cs 上添加自定义配置文件.其余基本相同.

If you are not in ASP.NET Core 2 yet, the process is almost the same. You just need to add the custom config file on Startup.cs. The rest is basically the same.

这篇关于如何将自定义 JSON 文件添加到 IConfiguration 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆