简体   繁体   中英

Getting values from appsettings.json

I tried getting value from my appsettings.json which is modeled like this:

 "ConfigurationModel": {
    "RfidAddress": "172.23.19.73",
    "BaudRate": "152000",
    "DataManagerTimeOut": "32000"
  }

Then I created a POCO like so:

public class ConfigurationModel
{
    public string RfidAddress { get; set; }
    public int BaudRate { get; set; }
    public int DataManagerTimeOut { get; set; }
}

In my Startup.cs I added the ConfigurationModel in the services like so:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.Configure<ConfigurationModel>(Configuration.GetSection("configurationModel"));

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    services.AddSignalR();
}

I created a class that utilized this settings like this:

public class RfidClass
{
    private readonly ConfigurationModel _configurationModel;

    public RfidClass(IOptions<ConfigurationModel> configurationModel)
    {
        _configurationModel = configurationModel.Value;
    }

    public void sas()
    {
        Console.WriteLine(_configurationModel.RfidAddress);
    }
}

Then in my Program.cs I need to call that class that I have just created like this:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
        SetRfid();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();

    public static void SetRfid()
    {
        var rfidClass = new RfidClass(); <-- MISSING ARGUMENT
    }
}

How can I pass the needed parameter to instantiate my RfidClass?

You should be able to extract the value by setting the result from the .Build() as follows:

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();
        host.Run();
        var config = host.Services.GetService<IConfiguration>();
        var configSection = config.GetSection("ConfigurationModel");
        var configModel = configSection.Get<ConfigurationModel>();
        SetRfid(configModel);
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();

    public static void SetRfid(ConfigurationModel configModel)
    {
        var rfidClass = new RfidClass(configModel); <-- ADDED
    }
}

I'm bit scared to say that Program and Startup classes are not meant to do such things. Usually such operations are called from some other classes, ie Controller classes. Post this, you can use dependency injection to pass the objects. Here is the code to do that:

public void ConfigureServices(IServiceCollection services) {

... services.Configure(Configuration.GetSection("configurationModel")); services.AddSingleton(m => { return new RfidClass(m.GetService>()); }); ... }

And here is the controller code:

public HomeController(ILogger<HomeController> logger, RfidClass rfidClass)
    {
        ...
    }

You appear to have everything set up correctly to use the Options Pattern, but are then trying to new up RfidClass rather than inject the options into a class like a Controller , View , Handler , or Middleware . These classes are unique in the sense that the framework can inject services into them.

    public class HomeController : Controller
   {

        private readonly RfidClass _rfidClass;

        public HomeController(IOptionsMonitor<ConfigurationModel> options)
        {
            _rFidClass= options.CurrentValue;
        }

        public IActionResult Index()
        {
            var rfidAddress = _rfidClass.rfidAddress;
            var baudRate = rfidClass.BaudRate;
           // do stuff.
            return View();
        }
    }

There is some great information int he microsoft documentation on utilizing the options pattern here https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM