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

iKn*_*ing 6 c# configuration json asp.net-core-mvc asp.net-core

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

所以,设置:

mysettings.json

{
  "MySettings": {
    "Name": "Some Name from config",
    "Description": "Some Description from config"
  }
}
Run Code Online (Sandbox Code Playgroud)

mysettings.cs

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

    public string Description { get; set; } = "Default description";
}
Run Code Online (Sandbox Code Playgroud)

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>();
}
Run Code Online (Sandbox Code Playgroud)

MysettingsService.cs

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

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

    public string GetName()
    {
        return mySettings.Name; 
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Lij*_*eph 16

几点:

  • 提到的类中缺少构造函数 - MysettingsService
  • 您是否在Startup类中注册了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; }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 定义MySettingsService

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

    services.Configure<MySettings>(this.Configuration.GetSection("MySettings"));
    services.AddSingleton<IMySettingsService, MySettingsService >();
    
    Run Code Online (Sandbox Code Playgroud)

编辑 - 我包括你要遵循的实施

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

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

  1. 创建设置文件 - mySettings.json- 包含内容
{
  "MySettings": {
    "Name": "Some Name from config",
    "Description": "Some Description from config"
  }
}
Run Code Online (Sandbox Code Playgroud)
  1. 在中配置它 Startup
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();
}
Run Code Online (Sandbox Code Playgroud)

看到这一行:

.AddJsonFile("mySettings.json",true,reloadOnChange:true)

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

        public string Description { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  1. 创建界面 IMySettingsService
namespace SettingsApp.Services
{
    public interface IMySettingsService
    {
        string GetName();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  1. 实现界面 - IMySettingsService
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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 添加选项,让系统知道您在Startup.ConfigureServices方法中的实现
// 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();
}
Run Code Online (Sandbox Code Playgroud)

注意包括所需的使用.

检查下面的代码是如何完成的:

// Options
services.AddOptions();
services.Configure<MySettings>(this.Configuration.GetSection("MySettings"));
services.AddSingleton<IMySettingsService, MySettingsService>();
Run Code Online (Sandbox Code Playgroud)
  1. 使用实现(我正在使用HomeController测试.)
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();
    }

...
Run Code Online (Sandbox Code Playgroud)
  1. 看结果:

家庭控制器构造函数 在行动里面