将IOptions传递到.Net核心中间件类以进行json配置检索

时间:2016-09-14 12:52:37

标签: c# json asp.net-core configuration asp.net-core-mvc

我正在尝试根据.net核心中的Options pattern使用强类型json配置设置。到目前为止,所有示例都显示了将强类型设置类注入控制器是多么容易,但是我需要在中间件类中使用它(非常类似于this question但是在尝试之后我没有进一步前进)。

所以,设置:

mysettings.json

{
  "MySettings": {
    "Name": "Some Name from config",
    "Description": "Some Description from config"
  }
}

mysettings.cs

public class MySettings
{
    public string Name { get; set; } = "Default name";

    public string Description { get; set; } = "Default description";
}

startup.cs

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

    // Add functionality to inject IOptions<T>
    services.AddOptions();

    // Add our Config object so it can be injected
    services.Configure<MySettings>(Configuration.GetSection("MySettings"));
    services.AddSingleton<IMySettingsService, MySettingsService>();
}

MysettingsService.cs

public class MysettingsService : IMysettingsService
{
    private MySettings mySettings { get; set; }

    public MysettingsService (MySettings _mySettings)
    {
        mySettings = _mySettings.value;
    }

    public string GetName()
    {
        return mySettings.Name; 
    }
}

如何实例化 MysettingsService.cs 并在类构造函数中注入IOptions<MySettings>以便我可以调用 GetName 方法?

2 个答案:

答案 0 :(得分:16)

几点:

  • 上述课程中缺少构造函数 - MysettingsService
  • 您是否在启动课程中注册了 IMysettingsService 的实施?
  • 在注册实施时,您可以初始化 MysettingsService ,如下所示: services.AddSingleton<IMysettingsService, MysettingsService >(i => new MysettingsService ());

请按照以下步骤操作:

  • 确保您已在ConfigurationBuilder
  • 中注册了JSON文件 - mysettings.json
  • 定义 MySettings

    public class MySettings
    {
        public string Name { get; set; }
    
        public string Description { get; set; }
    }
    
  • 定义 MySettingsService

    public class MySettingsService : IMySettingsService
    {
        private readonly MySettings mySettings;
    
        public MySettingsService (IOptions<MySettings> _mySettings)
        {
            mySettings = _mySettings.Value;
        }
    
        public string GetName()
        {
            return mySettings.Name; 
        }
    }
    
  • 在初创公司

    services.Configure<MySettings>(this.Configuration.GetSection("MySettings"));
    services.AddSingleton<IMySettingsService, MySettingsService >();
    

已编辑 - 我已将您的实施内容包括在内

我已经创建了一个示例应用程序,它对我有用;请按照以下步骤操作:

几个细节。 我的申请名称是:SettingsApp

  1. 使用内容
  2. 创建设置文件 - mySettings.json
    {
      "MySettings": {
        "Name": "Some Name from config",
        "Description": "Some Description from config"
      }
    }
    
    1. Startup
    2. 中配置它
      public Startup(IHostingEnvironment env)
      {
          var builder = new ConfigurationBuilder()
              .SetBasePath(env.ContentRootPath)
              .AddJsonFile("mySettings.json", true, reloadOnChange: true)
              .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
              .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
              .AddEnvironmentVariables();
      
          if (env.IsDevelopment())
          {
              // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
              builder.AddApplicationInsightsSettings(developerMode: true);
          }
          Configuration = builder.Build();
      }
      

      见行:

        

      .AddJsonFile(“mySettings.json”,true,reloadOnChange:true)

      1. 创建MySettings对象以保存设置
      2. namespace SettingsApp.Initialisations
        {
            public class MySettings
            {
                public string Name { get; set; }
        
                public string Description { get; set; }
            }
        }
        

        注意:我使用命名空间SettingsApp.Initialisations来保留此文件。您可以根据应用程序结构选择任何一种。

        1. 创建界面IMySettingsService
        2. namespace SettingsApp.Services
          {
              public interface IMySettingsService
              {
                  string GetName();
              }
          }
          

          注意:我使用命名空间SettingsApp.Services

          1. 实施界面 - IMySettingsService
          2. using SettingsApp.Initialisations;
            using Microsoft.Extensions.Options;
            
            namespace SettingsApp.Services
            {
                public class MySettingsService : IMySettingsService
                {
                    private readonly MySettings mySettings;
            
                    public MySettingsService(IOptions<MySettings> _mySettings)
                    {
                        mySettings = _mySettings.Value;
                    }
            
                    public string GetName()
                    {
                        return mySettings.Name;
                    }
                }
            }
            
            1. 添加选项,让系统了解您在Startup.ConfigureServices方法
            2. 中的实施情况
              // This method gets called by the run time. Use this method to add services to the container.
              public void ConfigureServices(IServiceCollection services)
              {
                  // Options
                  services.AddOptions();
                  services.Configure<MySettings>(this.Configuration.GetSection("MySettings"));
                  services.AddSingleton<IMySettingsService, MySettingsService>();
              
                  // Add framework services.
                  services.AddApplicationInsightsTelemetry(Configuration);
              
                  services.AddMvc();
              }
              

              请注意包含所需的使用。

              检查以下代码如何完成:

              // Options
              services.AddOptions();
              services.Configure<MySettings>(this.Configuration.GetSection("MySettings"));
              services.AddSingleton<IMySettingsService, MySettingsService>();
              
              1. 使用实现(我使用HomeController进行测试。)
              2. public class HomeController : Controller
                {
                    private IMySettingsService mySettingsService;
                
                    public HomeController(IMySettingsService settingsService)
                    {
                        mySettingsService = settingsService;
                    }
                
                    public IActionResult Index()
                    {
                        // Get the settings
                        var name = mySettingsService.GetName();
                
                        return View();
                    }
                
                ...
                
                1. 查看结果:
                2. Home controller constructor Inside the action

答案 1 :(得分:2)

在较新版本的.NET中,上面的绑定方法不再起作用了。

我创建了一个有效的扩展方法:

    public static void AddSettings<T>(this IServiceCollection serviceCollection, IConfiguration configuration) where T : class, new()
    {
        var settings = new T();
        configuration.Bind(typeof(T).Name, settings);
        serviceCollection.AddSingleton(settings);
    }

像这样使用:

services.AddSettings<LoggingSettings>(configuration);

完整示例:

        string pathToConfigFile = "c:\\config.json";
        IConfiguration configuration = new ConfigurationBuilder()
            .AddJsonFile(pathToConfigFile, optional: false, reloadOnChange: true)
            .Build();

        var services = new ServiceCollection()

        services.AddSingleton(configuration);

        services.AddSettings<ConnectionSettings>(configuration);
        services.AddSettings<LoggingSettings>(configuration);
        services.AddSettings<AutoCreateSettings>(configuration);